blob: 3d1fa434dca99e76682042bd4b3c11df62b472bd [file] [log] [blame]
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001//===--- SemaOverload.cpp - C++ Overloading ---------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file provides Sema routines for C++ overloading.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
John McCall5cebab12009-11-18 07:57:50 +000015#include "Lookup.h"
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000016#include "SemaInit.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000017#include "clang/Basic/Diagnostic.h"
Douglas Gregora11693b2008-11-12 17:17:38 +000018#include "clang/Lex/Preprocessor.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000019#include "clang/AST/ASTContext.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000020#include "clang/AST/CXXInheritance.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000021#include "clang/AST/Expr.h"
Douglas Gregor91cea0a2008-11-19 21:05:33 +000022#include "clang/AST/ExprCXX.h"
Douglas Gregora11693b2008-11-12 17:17:38 +000023#include "clang/AST/TypeOrdering.h"
Anders Carlssond624e162009-08-26 23:45:07 +000024#include "clang/Basic/PartialDiagnostic.h"
Douglas Gregor58e008d2008-11-13 20:12:29 +000025#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregor55297ac2008-12-23 00:26:44 +000026#include "llvm/ADT/STLExtras.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000027#include <algorithm>
28
29namespace clang {
30
31/// GetConversionCategory - Retrieve the implicit conversion
32/// category corresponding to the given implicit conversion kind.
Mike Stump11289f42009-09-09 15:08:12 +000033ImplicitConversionCategory
Douglas Gregor5251f1b2008-10-21 16:13:35 +000034GetConversionCategory(ImplicitConversionKind Kind) {
35 static const ImplicitConversionCategory
36 Category[(int)ICK_Num_Conversion_Kinds] = {
37 ICC_Identity,
38 ICC_Lvalue_Transformation,
39 ICC_Lvalue_Transformation,
40 ICC_Lvalue_Transformation,
Douglas Gregor40cb9ad2009-12-09 00:47:37 +000041 ICC_Identity,
Douglas Gregor5251f1b2008-10-21 16:13:35 +000042 ICC_Qualification_Adjustment,
43 ICC_Promotion,
44 ICC_Promotion,
Douglas Gregor78ca74d2009-02-12 00:15:05 +000045 ICC_Promotion,
46 ICC_Conversion,
47 ICC_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +000048 ICC_Conversion,
49 ICC_Conversion,
50 ICC_Conversion,
51 ICC_Conversion,
52 ICC_Conversion,
Douglas Gregor786ab212008-10-29 02:00:59 +000053 ICC_Conversion,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +000054 ICC_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +000055 ICC_Conversion
56 };
57 return Category[(int)Kind];
58}
59
60/// GetConversionRank - Retrieve the implicit conversion rank
61/// corresponding to the given implicit conversion kind.
62ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) {
63 static const ImplicitConversionRank
64 Rank[(int)ICK_Num_Conversion_Kinds] = {
65 ICR_Exact_Match,
66 ICR_Exact_Match,
67 ICR_Exact_Match,
68 ICR_Exact_Match,
69 ICR_Exact_Match,
Douglas Gregor40cb9ad2009-12-09 00:47:37 +000070 ICR_Exact_Match,
Douglas Gregor5251f1b2008-10-21 16:13:35 +000071 ICR_Promotion,
72 ICR_Promotion,
Douglas Gregor78ca74d2009-02-12 00:15:05 +000073 ICR_Promotion,
74 ICR_Conversion,
75 ICR_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +000076 ICR_Conversion,
77 ICR_Conversion,
78 ICR_Conversion,
79 ICR_Conversion,
80 ICR_Conversion,
Douglas Gregor786ab212008-10-29 02:00:59 +000081 ICR_Conversion,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +000082 ICR_Conversion,
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +000083 ICR_Complex_Real_Conversion
Douglas Gregor5251f1b2008-10-21 16:13:35 +000084 };
85 return Rank[(int)Kind];
86}
87
88/// GetImplicitConversionName - Return the name of this kind of
89/// implicit conversion.
90const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
Nuno Lopescfca1f02009-12-23 17:49:57 +000091 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
Douglas Gregor5251f1b2008-10-21 16:13:35 +000092 "No conversion",
93 "Lvalue-to-rvalue",
94 "Array-to-pointer",
95 "Function-to-pointer",
Douglas Gregor40cb9ad2009-12-09 00:47:37 +000096 "Noreturn adjustment",
Douglas Gregor5251f1b2008-10-21 16:13:35 +000097 "Qualification",
98 "Integral promotion",
99 "Floating point promotion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000100 "Complex promotion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000101 "Integral conversion",
102 "Floating conversion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000103 "Complex conversion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000104 "Floating-integral conversion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000105 "Complex-real conversion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000106 "Pointer conversion",
107 "Pointer-to-member conversion",
Douglas Gregor786ab212008-10-29 02:00:59 +0000108 "Boolean conversion",
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000109 "Compatible-types conversion",
Douglas Gregor786ab212008-10-29 02:00:59 +0000110 "Derived-to-base conversion"
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000111 };
112 return Name[Kind];
113}
114
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000115/// StandardConversionSequence - Set the standard conversion
116/// sequence to the identity conversion.
117void StandardConversionSequence::setAsIdentityConversion() {
118 First = ICK_Identity;
119 Second = ICK_Identity;
120 Third = ICK_Identity;
Douglas Gregore489a7d2010-02-28 18:30:25 +0000121 DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000122 ReferenceBinding = false;
123 DirectBinding = false;
Sebastian Redlf69a94a2009-03-29 22:46:24 +0000124 RRefBinding = false;
Douglas Gregor2fe98832008-11-03 19:09:14 +0000125 CopyConstructor = 0;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000126}
127
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000128/// getRank - Retrieve the rank of this standard conversion sequence
129/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
130/// implicit conversions.
131ImplicitConversionRank StandardConversionSequence::getRank() const {
132 ImplicitConversionRank Rank = ICR_Exact_Match;
133 if (GetConversionRank(First) > Rank)
134 Rank = GetConversionRank(First);
135 if (GetConversionRank(Second) > Rank)
136 Rank = GetConversionRank(Second);
137 if (GetConversionRank(Third) > Rank)
138 Rank = GetConversionRank(Third);
139 return Rank;
140}
141
142/// isPointerConversionToBool - Determines whether this conversion is
143/// a conversion of a pointer or pointer-to-member to bool. This is
Mike Stump11289f42009-09-09 15:08:12 +0000144/// used as part of the ranking of standard conversion sequences
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000145/// (C++ 13.3.3.2p4).
Mike Stump11289f42009-09-09 15:08:12 +0000146bool StandardConversionSequence::isPointerConversionToBool() const {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000147 // Note that FromType has not necessarily been transformed by the
148 // array-to-pointer or function-to-pointer implicit conversions, so
149 // check for their presence as well as checking whether FromType is
150 // a pointer.
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000151 if (getToType(1)->isBooleanType() &&
John McCall0d1da222010-01-12 00:44:57 +0000152 (getFromType()->isPointerType() || getFromType()->isBlockPointerType() ||
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000153 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
154 return true;
155
156 return false;
157}
158
Douglas Gregor5c407d92008-10-23 00:40:37 +0000159/// isPointerConversionToVoidPointer - Determines whether this
160/// conversion is a conversion of a pointer to a void pointer. This is
161/// used as part of the ranking of standard conversion sequences (C++
162/// 13.3.3.2p4).
Mike Stump11289f42009-09-09 15:08:12 +0000163bool
Douglas Gregor5c407d92008-10-23 00:40:37 +0000164StandardConversionSequence::
Mike Stump11289f42009-09-09 15:08:12 +0000165isPointerConversionToVoidPointer(ASTContext& Context) const {
John McCall0d1da222010-01-12 00:44:57 +0000166 QualType FromType = getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000167 QualType ToType = getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +0000168
169 // Note that FromType has not necessarily been transformed by the
170 // array-to-pointer implicit conversion, so check for its presence
171 // and redo the conversion to get a pointer.
172 if (First == ICK_Array_To_Pointer)
173 FromType = Context.getArrayDecayedType(FromType);
174
Douglas Gregor1aa450a2009-12-13 21:37:05 +0000175 if (Second == ICK_Pointer_Conversion && FromType->isPointerType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000176 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
Douglas Gregor5c407d92008-10-23 00:40:37 +0000177 return ToPtrType->getPointeeType()->isVoidType();
178
179 return false;
180}
181
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000182/// DebugPrint - Print this standard conversion sequence to standard
183/// error. Useful for debugging overloading issues.
184void StandardConversionSequence::DebugPrint() const {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000185 llvm::raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000186 bool PrintedSomething = false;
187 if (First != ICK_Identity) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000188 OS << GetImplicitConversionName(First);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000189 PrintedSomething = true;
190 }
191
192 if (Second != ICK_Identity) {
193 if (PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000194 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000195 }
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000196 OS << GetImplicitConversionName(Second);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000197
198 if (CopyConstructor) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000199 OS << " (by copy constructor)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000200 } else if (DirectBinding) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000201 OS << " (direct reference binding)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000202 } else if (ReferenceBinding) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000203 OS << " (reference binding)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000204 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000205 PrintedSomething = true;
206 }
207
208 if (Third != ICK_Identity) {
209 if (PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000210 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000211 }
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000212 OS << GetImplicitConversionName(Third);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000213 PrintedSomething = true;
214 }
215
216 if (!PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000217 OS << "No conversions required";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000218 }
219}
220
221/// DebugPrint - Print this user-defined conversion sequence to standard
222/// error. Useful for debugging overloading issues.
223void UserDefinedConversionSequence::DebugPrint() const {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000224 llvm::raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000225 if (Before.First || Before.Second || Before.Third) {
226 Before.DebugPrint();
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000227 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000228 }
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000229 OS << "'" << ConversionFunction->getNameAsString() << "'";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000230 if (After.First || After.Second || After.Third) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000231 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000232 After.DebugPrint();
233 }
234}
235
236/// DebugPrint - Print this implicit conversion sequence to standard
237/// error. Useful for debugging overloading issues.
238void ImplicitConversionSequence::DebugPrint() const {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000239 llvm::raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000240 switch (ConversionKind) {
241 case StandardConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000242 OS << "Standard conversion: ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000243 Standard.DebugPrint();
244 break;
245 case UserDefinedConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000246 OS << "User-defined conversion: ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000247 UserDefined.DebugPrint();
248 break;
249 case EllipsisConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000250 OS << "Ellipsis conversion";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000251 break;
John McCall0d1da222010-01-12 00:44:57 +0000252 case AmbiguousConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000253 OS << "Ambiguous conversion";
John McCall0d1da222010-01-12 00:44:57 +0000254 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000255 case BadConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000256 OS << "Bad conversion";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000257 break;
258 }
259
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000260 OS << "\n";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000261}
262
John McCall0d1da222010-01-12 00:44:57 +0000263void AmbiguousConversionSequence::construct() {
264 new (&conversions()) ConversionSet();
265}
266
267void AmbiguousConversionSequence::destruct() {
268 conversions().~ConversionSet();
269}
270
271void
272AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
273 FromTypePtr = O.FromTypePtr;
274 ToTypePtr = O.ToTypePtr;
275 new (&conversions()) ConversionSet(O.conversions());
276}
277
278
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000279// IsOverload - Determine whether the given New declaration is an
John McCall3d988d92009-12-02 08:47:38 +0000280// overload of the declarations in Old. This routine returns false if
281// New and Old cannot be overloaded, e.g., if New has the same
282// signature as some function in Old (C++ 1.3.10) or if the Old
283// declarations aren't functions (or function templates) at all. When
John McCalldaa3d6b2009-12-09 03:35:25 +0000284// it does return false, MatchedDecl will point to the decl that New
285// cannot be overloaded with. This decl may be a UsingShadowDecl on
286// top of the underlying declaration.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000287//
288// Example: Given the following input:
289//
290// void f(int, float); // #1
291// void f(int, int); // #2
292// int f(int, int); // #3
293//
294// When we process #1, there is no previous declaration of "f",
Mike Stump11289f42009-09-09 15:08:12 +0000295// so IsOverload will not be used.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000296//
John McCall3d988d92009-12-02 08:47:38 +0000297// When we process #2, Old contains only the FunctionDecl for #1. By
298// comparing the parameter types, we see that #1 and #2 are overloaded
299// (since they have different signatures), so this routine returns
300// false; MatchedDecl is unchanged.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000301//
John McCall3d988d92009-12-02 08:47:38 +0000302// When we process #3, Old is an overload set containing #1 and #2. We
303// compare the signatures of #3 to #1 (they're overloaded, so we do
304// nothing) and then #3 to #2. Since the signatures of #3 and #2 are
305// identical (return types of functions are not part of the
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000306// signature), IsOverload returns false and MatchedDecl will be set to
307// point to the FunctionDecl for #2.
John McCalldaa3d6b2009-12-09 03:35:25 +0000308Sema::OverloadKind
John McCall84d87672009-12-10 09:41:52 +0000309Sema::CheckOverload(FunctionDecl *New, const LookupResult &Old,
310 NamedDecl *&Match) {
John McCall3d988d92009-12-02 08:47:38 +0000311 for (LookupResult::iterator I = Old.begin(), E = Old.end();
John McCall1f82f242009-11-18 22:49:29 +0000312 I != E; ++I) {
John McCall3d988d92009-12-02 08:47:38 +0000313 NamedDecl *OldD = (*I)->getUnderlyingDecl();
314 if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(OldD)) {
John McCall1f82f242009-11-18 22:49:29 +0000315 if (!IsOverload(New, OldT->getTemplatedDecl())) {
John McCalldaa3d6b2009-12-09 03:35:25 +0000316 Match = *I;
317 return Ovl_Match;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000318 }
John McCall3d988d92009-12-02 08:47:38 +0000319 } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(OldD)) {
John McCall1f82f242009-11-18 22:49:29 +0000320 if (!IsOverload(New, OldF)) {
John McCalldaa3d6b2009-12-09 03:35:25 +0000321 Match = *I;
322 return Ovl_Match;
John McCall1f82f242009-11-18 22:49:29 +0000323 }
John McCall84d87672009-12-10 09:41:52 +0000324 } else if (isa<UsingDecl>(OldD) || isa<TagDecl>(OldD)) {
325 // We can overload with these, which can show up when doing
326 // redeclaration checks for UsingDecls.
327 assert(Old.getLookupKind() == LookupUsingDeclName);
328 } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
329 // Optimistically assume that an unresolved using decl will
330 // overload; if it doesn't, we'll have to diagnose during
331 // template instantiation.
332 } else {
John McCall1f82f242009-11-18 22:49:29 +0000333 // (C++ 13p1):
334 // Only function declarations can be overloaded; object and type
335 // declarations cannot be overloaded.
John McCalldaa3d6b2009-12-09 03:35:25 +0000336 Match = *I;
337 return Ovl_NonFunction;
John McCall1f82f242009-11-18 22:49:29 +0000338 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000339 }
John McCall1f82f242009-11-18 22:49:29 +0000340
John McCalldaa3d6b2009-12-09 03:35:25 +0000341 return Ovl_Overload;
John McCall1f82f242009-11-18 22:49:29 +0000342}
343
344bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old) {
345 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
346 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
347
348 // C++ [temp.fct]p2:
349 // A function template can be overloaded with other function templates
350 // and with normal (non-template) functions.
351 if ((OldTemplate == 0) != (NewTemplate == 0))
352 return true;
353
354 // Is the function New an overload of the function Old?
355 QualType OldQType = Context.getCanonicalType(Old->getType());
356 QualType NewQType = Context.getCanonicalType(New->getType());
357
358 // Compare the signatures (C++ 1.3.10) of the two functions to
359 // determine whether they are overloads. If we find any mismatch
360 // in the signature, they are overloads.
361
362 // If either of these functions is a K&R-style function (no
363 // prototype), then we consider them to have matching signatures.
364 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
365 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
366 return false;
367
368 FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
369 FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
370
371 // The signature of a function includes the types of its
372 // parameters (C++ 1.3.10), which includes the presence or absence
373 // of the ellipsis; see C++ DR 357).
374 if (OldQType != NewQType &&
375 (OldType->getNumArgs() != NewType->getNumArgs() ||
376 OldType->isVariadic() != NewType->isVariadic() ||
377 !std::equal(OldType->arg_type_begin(), OldType->arg_type_end(),
378 NewType->arg_type_begin())))
379 return true;
380
381 // C++ [temp.over.link]p4:
382 // The signature of a function template consists of its function
383 // signature, its return type and its template parameter list. The names
384 // of the template parameters are significant only for establishing the
385 // relationship between the template parameters and the rest of the
386 // signature.
387 //
388 // We check the return type and template parameter lists for function
389 // templates first; the remaining checks follow.
390 if (NewTemplate &&
391 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
392 OldTemplate->getTemplateParameters(),
393 false, TPL_TemplateMatch) ||
394 OldType->getResultType() != NewType->getResultType()))
395 return true;
396
397 // If the function is a class member, its signature includes the
398 // cv-qualifiers (if any) on the function itself.
399 //
400 // As part of this, also check whether one of the member functions
401 // is static, in which case they are not overloads (C++
402 // 13.1p2). While not part of the definition of the signature,
403 // this check is important to determine whether these functions
404 // can be overloaded.
405 CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
406 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
407 if (OldMethod && NewMethod &&
408 !OldMethod->isStatic() && !NewMethod->isStatic() &&
409 OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers())
410 return true;
411
412 // The signatures match; this is not an overload.
413 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000414}
415
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000416/// TryImplicitConversion - Attempt to perform an implicit conversion
417/// from the given expression (Expr) to the given type (ToType). This
418/// function returns an implicit conversion sequence that can be used
419/// to perform the initialization. Given
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000420///
421/// void f(float f);
422/// void g(int i) { f(i); }
423///
424/// this routine would produce an implicit conversion sequence to
425/// describe the initialization of f from i, which will be a standard
426/// conversion sequence containing an lvalue-to-rvalue conversion (C++
427/// 4.1) followed by a floating-integral conversion (C++ 4.9).
428//
429/// Note that this routine only determines how the conversion can be
430/// performed; it does not actually perform the conversion. As such,
431/// it will not produce any diagnostics if no conversion is available,
432/// but will instead return an implicit conversion sequence of kind
433/// "BadConversion".
Douglas Gregor2fe98832008-11-03 19:09:14 +0000434///
435/// If @p SuppressUserConversions, then user-defined conversions are
436/// not permitted.
Douglas Gregor5fb53972009-01-14 15:45:31 +0000437/// If @p AllowExplicit, then explicit user-defined conversions are
438/// permitted.
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +0000439/// If @p UserCast, the implicit conversion is being done for a user-specified
440/// cast.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000441ImplicitConversionSequence
Anders Carlsson5ec4abf2009-08-27 17:14:02 +0000442Sema::TryImplicitConversion(Expr* From, QualType ToType,
443 bool SuppressUserConversions,
Douglas Gregore81335c2010-04-16 18:00:29 +0000444 bool AllowExplicit,
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +0000445 bool InOverloadResolution,
446 bool UserCast) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000447 ImplicitConversionSequence ICS;
John McCallbc077cf2010-02-08 23:07:23 +0000448 if (IsStandardConversion(From, ToType, InOverloadResolution, ICS.Standard)) {
John McCall0d1da222010-01-12 00:44:57 +0000449 ICS.setStandard();
John McCallbc077cf2010-02-08 23:07:23 +0000450 return ICS;
451 }
452
453 if (!getLangOptions().CPlusPlus) {
John McCall65eb8792010-02-25 01:37:24 +0000454 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
John McCallbc077cf2010-02-08 23:07:23 +0000455 return ICS;
456 }
457
458 OverloadCandidateSet Conversions(From->getExprLoc());
459 OverloadingResult UserDefResult
460 = IsUserDefinedConversion(From, ToType, ICS.UserDefined, Conversions,
461 !SuppressUserConversions, AllowExplicit,
Douglas Gregor7b23e412010-04-16 17:25:05 +0000462 UserCast);
John McCallbc077cf2010-02-08 23:07:23 +0000463
464 if (UserDefResult == OR_Success) {
John McCall0d1da222010-01-12 00:44:57 +0000465 ICS.setUserDefined();
Douglas Gregor05379422008-11-03 17:51:48 +0000466 // C++ [over.ics.user]p4:
467 // A conversion of an expression of class type to the same class
468 // type is given Exact Match rank, and a conversion of an
469 // expression of class type to a base class of that type is
470 // given Conversion rank, in spite of the fact that a copy
471 // constructor (i.e., a user-defined conversion function) is
472 // called for those cases.
Mike Stump11289f42009-09-09 15:08:12 +0000473 if (CXXConstructorDecl *Constructor
Douglas Gregor05379422008-11-03 17:51:48 +0000474 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
Mike Stump11289f42009-09-09 15:08:12 +0000475 QualType FromCanon
Douglas Gregorbb2e68832009-02-02 22:11:10 +0000476 = Context.getCanonicalType(From->getType().getUnqualifiedType());
477 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
Douglas Gregor507eb872009-12-22 00:34:07 +0000478 if (Constructor->isCopyConstructor() &&
Douglas Gregor4141d5b2009-12-22 00:21:20 +0000479 (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon))) {
Douglas Gregor2fe98832008-11-03 19:09:14 +0000480 // Turn this into a "standard" conversion sequence, so that it
481 // gets ranked with standard conversion sequences.
John McCall0d1da222010-01-12 00:44:57 +0000482 ICS.setStandard();
Douglas Gregor05379422008-11-03 17:51:48 +0000483 ICS.Standard.setAsIdentityConversion();
John McCall0d1da222010-01-12 00:44:57 +0000484 ICS.Standard.setFromType(From->getType());
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000485 ICS.Standard.setAllToTypes(ToType);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000486 ICS.Standard.CopyConstructor = Constructor;
Douglas Gregorbb2e68832009-02-02 22:11:10 +0000487 if (ToCanon != FromCanon)
Douglas Gregor05379422008-11-03 17:51:48 +0000488 ICS.Standard.Second = ICK_Derived_To_Base;
489 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000490 }
Douglas Gregor576e98c2009-01-30 23:27:23 +0000491
492 // C++ [over.best.ics]p4:
493 // However, when considering the argument of a user-defined
494 // conversion function that is a candidate by 13.3.1.3 when
495 // invoked for the copying of the temporary in the second step
496 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
497 // 13.3.1.6 in all cases, only standard conversion sequences and
498 // ellipsis conversion sequences are allowed.
John McCall6a61b522010-01-13 09:16:55 +0000499 if (SuppressUserConversions && ICS.isUserDefined()) {
John McCall65eb8792010-02-25 01:37:24 +0000500 ICS.setBad(BadConversionSequence::suppressed_user, From, ToType);
John McCall6a61b522010-01-13 09:16:55 +0000501 }
John McCalle8c8cd22010-01-13 22:30:33 +0000502 } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) {
John McCall0d1da222010-01-12 00:44:57 +0000503 ICS.setAmbiguous();
504 ICS.Ambiguous.setFromType(From->getType());
505 ICS.Ambiguous.setToType(ToType);
506 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
507 Cand != Conversions.end(); ++Cand)
508 if (Cand->Viable)
509 ICS.Ambiguous.addConversion(Cand->Function);
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000510 } else {
John McCall65eb8792010-02-25 01:37:24 +0000511 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000512 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000513
514 return ICS;
515}
516
Douglas Gregorae4b5df2010-04-16 22:27:05 +0000517/// PerformImplicitConversion - Perform an implicit conversion of the
518/// expression From to the type ToType. Returns true if there was an
519/// error, false otherwise. The expression From is replaced with the
520/// converted expression. Flavor is the kind of conversion we're
521/// performing, used in the error message. If @p AllowExplicit,
522/// explicit user-defined conversions are permitted.
523bool
524Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
525 AssignmentAction Action, bool AllowExplicit) {
526 ImplicitConversionSequence ICS;
527 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
528}
529
530bool
531Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
532 AssignmentAction Action, bool AllowExplicit,
533 ImplicitConversionSequence& ICS) {
534 ICS = TryImplicitConversion(From, ToType,
535 /*SuppressUserConversions=*/false,
536 AllowExplicit,
537 /*InOverloadResolution=*/false);
538 return PerformImplicitConversion(From, ToType, ICS, Action);
539}
540
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000541/// \brief Determine whether the conversion from FromType to ToType is a valid
542/// conversion that strips "noreturn" off the nested function type.
543static bool IsNoReturnConversion(ASTContext &Context, QualType FromType,
544 QualType ToType, QualType &ResultTy) {
545 if (Context.hasSameUnqualifiedType(FromType, ToType))
546 return false;
547
548 // Strip the noreturn off the type we're converting from; noreturn can
549 // safely be removed.
550 FromType = Context.getNoReturnType(FromType, false);
551 if (!Context.hasSameUnqualifiedType(FromType, ToType))
552 return false;
553
554 ResultTy = FromType;
555 return true;
556}
557
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000558/// IsStandardConversion - Determines whether there is a standard
559/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
560/// expression From to the type ToType. Standard conversion sequences
561/// only consider non-class types; for conversions that involve class
562/// types, use TryImplicitConversion. If a conversion exists, SCS will
563/// contain the standard conversion sequence required to perform this
564/// conversion and this routine will return true. Otherwise, this
565/// routine will return false and the value of SCS is unspecified.
Mike Stump11289f42009-09-09 15:08:12 +0000566bool
567Sema::IsStandardConversion(Expr* From, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +0000568 bool InOverloadResolution,
Mike Stump11289f42009-09-09 15:08:12 +0000569 StandardConversionSequence &SCS) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000570 QualType FromType = From->getType();
571
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000572 // Standard conversions (C++ [conv])
Douglas Gregora11693b2008-11-12 17:17:38 +0000573 SCS.setAsIdentityConversion();
Douglas Gregore489a7d2010-02-28 18:30:25 +0000574 SCS.DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor47d3f272008-12-19 17:40:08 +0000575 SCS.IncompatibleObjC = false;
John McCall0d1da222010-01-12 00:44:57 +0000576 SCS.setFromType(FromType);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000577 SCS.CopyConstructor = 0;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000578
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000579 // There are no standard conversions for class types in C++, so
Mike Stump11289f42009-09-09 15:08:12 +0000580 // abort early. When overloading in C, however, we do permit
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000581 if (FromType->isRecordType() || ToType->isRecordType()) {
582 if (getLangOptions().CPlusPlus)
583 return false;
584
Mike Stump11289f42009-09-09 15:08:12 +0000585 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000586 }
587
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000588 // The first conversion can be an lvalue-to-rvalue conversion,
589 // array-to-pointer conversion, or function-to-pointer conversion
590 // (C++ 4p1).
591
John McCall16df1e52010-03-30 21:47:33 +0000592 DeclAccessPair AccessPair;
593
Mike Stump11289f42009-09-09 15:08:12 +0000594 // Lvalue-to-rvalue conversion (C++ 4.1):
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000595 // An lvalue (3.10) of a non-function, non-array type T can be
596 // converted to an rvalue.
597 Expr::isLvalueResult argIsLvalue = From->isLvalue(Context);
Mike Stump11289f42009-09-09 15:08:12 +0000598 if (argIsLvalue == Expr::LV_Valid &&
Douglas Gregorcd695e52008-11-10 20:40:00 +0000599 !FromType->isFunctionType() && !FromType->isArrayType() &&
Douglas Gregor1baf54e2009-03-13 18:40:31 +0000600 Context.getCanonicalType(FromType) != Context.OverloadTy) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000601 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000602
603 // If T is a non-class type, the type of the rvalue is the
604 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000605 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
606 // just strip the qualifiers because they don't matter.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000607 FromType = FromType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000608 } else if (FromType->isArrayType()) {
609 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000610 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000611
612 // An lvalue or rvalue of type "array of N T" or "array of unknown
613 // bound of T" can be converted to an rvalue of type "pointer to
614 // T" (C++ 4.2p1).
615 FromType = Context.getArrayDecayedType(FromType);
616
617 if (IsStringLiteralToNonConstPointerConversion(From, ToType)) {
618 // This conversion is deprecated. (C++ D.4).
Douglas Gregore489a7d2010-02-28 18:30:25 +0000619 SCS.DeprecatedStringLiteralToCharPtr = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000620
621 // For the purpose of ranking in overload resolution
622 // (13.3.3.1.1), this conversion is considered an
623 // array-to-pointer conversion followed by a qualification
624 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000625 SCS.Second = ICK_Identity;
626 SCS.Third = ICK_Qualification;
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000627 SCS.setAllToTypes(FromType);
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000628 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000629 }
Mike Stump12b8ce12009-08-04 21:02:39 +0000630 } else if (FromType->isFunctionType() && argIsLvalue == Expr::LV_Valid) {
631 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000632 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000633
634 // An lvalue of function type T can be converted to an rvalue of
635 // type "pointer to T." The result is a pointer to the
636 // function. (C++ 4.3p1).
637 FromType = Context.getPointerType(FromType);
Douglas Gregor064fdb22010-04-14 23:11:21 +0000638 } else if (From->getType() == Context.OverloadTy) {
639 if (FunctionDecl *Fn
640 = ResolveAddressOfOverloadedFunction(From, ToType, false,
641 AccessPair)) {
642 // Address of overloaded function (C++ [over.over]).
643 SCS.First = ICK_Function_To_Pointer;
Douglas Gregorcd695e52008-11-10 20:40:00 +0000644
Douglas Gregor064fdb22010-04-14 23:11:21 +0000645 // We were able to resolve the address of the overloaded function,
646 // so we can convert to the type of that function.
647 FromType = Fn->getType();
648 if (ToType->isLValueReferenceType())
649 FromType = Context.getLValueReferenceType(FromType);
650 else if (ToType->isRValueReferenceType())
651 FromType = Context.getRValueReferenceType(FromType);
652 else if (ToType->isMemberPointerType()) {
653 // Resolve address only succeeds if both sides are member pointers,
654 // but it doesn't have to be the same class. See DR 247.
655 // Note that this means that the type of &Derived::fn can be
656 // Ret (Base::*)(Args) if the fn overload actually found is from the
657 // base class, even if it was brought into the derived class via a
658 // using declaration. The standard isn't clear on this issue at all.
659 CXXMethodDecl *M = cast<CXXMethodDecl>(Fn);
660 FromType = Context.getMemberPointerType(FromType,
661 Context.getTypeDeclType(M->getParent()).getTypePtr());
662 } else {
663 FromType = Context.getPointerType(FromType);
664 }
665 } else {
666 return false;
667 }
Mike Stump12b8ce12009-08-04 21:02:39 +0000668 } else {
669 // We don't require any conversions for the first step.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000670 SCS.First = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000671 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000672 SCS.setToType(0, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000673
674 // The second conversion can be an integral promotion, floating
675 // point promotion, integral conversion, floating point conversion,
676 // floating-integral conversion, pointer conversion,
677 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000678 // For overloading in C, this can also be a "compatible-type"
679 // conversion.
Douglas Gregor47d3f272008-12-19 17:40:08 +0000680 bool IncompatibleObjC = false;
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000681 if (Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000682 // The unqualified versions of the types are the same: there's no
683 // conversion to do.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000684 SCS.Second = ICK_Identity;
Mike Stump12b8ce12009-08-04 21:02:39 +0000685 } else if (IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump11289f42009-09-09 15:08:12 +0000686 // Integral promotion (C++ 4.5).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000687 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000688 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000689 } else if (IsFloatingPointPromotion(FromType, ToType)) {
690 // Floating point promotion (C++ 4.6).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000691 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000692 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000693 } else if (IsComplexPromotion(FromType, ToType)) {
694 // Complex promotion (Clang extension)
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000695 SCS.Second = ICK_Complex_Promotion;
696 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000697 } else if ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000698 (ToType->isIntegralType() && !ToType->isEnumeralType())) {
Mike Stump12b8ce12009-08-04 21:02:39 +0000699 // Integral conversions (C++ 4.7).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000700 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000701 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000702 } else if (FromType->isComplexType() && ToType->isComplexType()) {
703 // Complex conversions (C99 6.3.1.6)
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000704 SCS.Second = ICK_Complex_Conversion;
705 FromType = ToType.getUnqualifiedType();
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +0000706 } else if ((FromType->isComplexType() && ToType->isArithmeticType()) ||
707 (ToType->isComplexType() && FromType->isArithmeticType())) {
708 // Complex-real conversions (C99 6.3.1.7)
709 SCS.Second = ICK_Complex_Real;
710 FromType = ToType.getUnqualifiedType();
711 } else if (FromType->isFloatingType() && ToType->isFloatingType()) {
712 // Floating point conversions (C++ 4.8).
713 SCS.Second = ICK_Floating_Conversion;
714 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000715 } else if ((FromType->isFloatingType() &&
716 ToType->isIntegralType() && (!ToType->isBooleanType() &&
717 !ToType->isEnumeralType())) ||
Mike Stump11289f42009-09-09 15:08:12 +0000718 ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
Mike Stump12b8ce12009-08-04 21:02:39 +0000719 ToType->isFloatingType())) {
720 // Floating-integral conversions (C++ 4.9).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000721 SCS.Second = ICK_Floating_Integral;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000722 FromType = ToType.getUnqualifiedType();
Anders Carlsson228eea32009-08-28 15:33:32 +0000723 } else if (IsPointerConversion(From, FromType, ToType, InOverloadResolution,
724 FromType, IncompatibleObjC)) {
Mike Stump12b8ce12009-08-04 21:02:39 +0000725 // Pointer conversions (C++ 4.10).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000726 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor47d3f272008-12-19 17:40:08 +0000727 SCS.IncompatibleObjC = IncompatibleObjC;
Douglas Gregor56751b52009-09-25 04:25:58 +0000728 } else if (IsMemberPointerConversion(From, FromType, ToType,
729 InOverloadResolution, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +0000730 // Pointer to member conversions (4.11).
Sebastian Redl72b597d2009-01-25 19:43:20 +0000731 SCS.Second = ICK_Pointer_Member;
Mike Stump12b8ce12009-08-04 21:02:39 +0000732 } else if (ToType->isBooleanType() &&
733 (FromType->isArithmeticType() ||
734 FromType->isEnumeralType() ||
Fariborz Jahanian88118852009-12-11 21:23:13 +0000735 FromType->isAnyPointerType() ||
Mike Stump12b8ce12009-08-04 21:02:39 +0000736 FromType->isBlockPointerType() ||
737 FromType->isMemberPointerType() ||
738 FromType->isNullPtrType())) {
739 // Boolean conversions (C++ 4.12).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000740 SCS.Second = ICK_Boolean_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000741 FromType = Context.BoolTy;
Mike Stump11289f42009-09-09 15:08:12 +0000742 } else if (!getLangOptions().CPlusPlus &&
Mike Stump12b8ce12009-08-04 21:02:39 +0000743 Context.typesAreCompatible(ToType, FromType)) {
744 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000745 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000746 } else if (IsNoReturnConversion(Context, FromType, ToType, FromType)) {
747 // Treat a conversion that strips "noreturn" as an identity conversion.
748 SCS.Second = ICK_NoReturn_Adjustment;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000749 } else {
750 // No second conversion required.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000751 SCS.Second = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000752 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000753 SCS.setToType(1, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000754
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000755 QualType CanonFrom;
756 QualType CanonTo;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000757 // The third conversion can be a qualification conversion (C++ 4p1).
Douglas Gregor9a657932008-10-21 23:43:52 +0000758 if (IsQualificationConversion(FromType, ToType)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000759 SCS.Third = ICK_Qualification;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000760 FromType = ToType;
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000761 CanonFrom = Context.getCanonicalType(FromType);
762 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000763 } else {
764 // No conversion required
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000765 SCS.Third = ICK_Identity;
766
Mike Stump11289f42009-09-09 15:08:12 +0000767 // C++ [over.best.ics]p6:
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000768 // [...] Any difference in top-level cv-qualification is
769 // subsumed by the initialization itself and does not constitute
770 // a conversion. [...]
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000771 CanonFrom = Context.getCanonicalType(FromType);
Mike Stump11289f42009-09-09 15:08:12 +0000772 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +0000773 if (CanonFrom.getLocalUnqualifiedType()
774 == CanonTo.getLocalUnqualifiedType() &&
775 CanonFrom.getLocalCVRQualifiers() != CanonTo.getLocalCVRQualifiers()) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000776 FromType = ToType;
777 CanonFrom = CanonTo;
778 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000779 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000780 SCS.setToType(2, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000781
782 // If we have not converted the argument type to the parameter type,
783 // this is a bad conversion sequence.
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000784 if (CanonFrom != CanonTo)
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000785 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000786
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000787 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000788}
789
790/// IsIntegralPromotion - Determines whether the conversion from the
791/// expression From (whose potentially-adjusted type is FromType) to
792/// ToType is an integral promotion (C++ 4.5). If so, returns true and
793/// sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +0000794bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +0000795 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlee547972008-11-04 15:59:10 +0000796 // All integers are built-in.
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000797 if (!To) {
798 return false;
799 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000800
801 // An rvalue of type char, signed char, unsigned char, short int, or
802 // unsigned short int can be converted to an rvalue of type int if
803 // int can represent all the values of the source type; otherwise,
804 // the source rvalue can be converted to an rvalue of type unsigned
805 // int (C++ 4.5p1).
Douglas Gregora71cc152010-02-02 20:10:50 +0000806 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
807 !FromType->isEnumeralType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000808 if (// We can promote any signed, promotable integer type to an int
809 (FromType->isSignedIntegerType() ||
810 // We can promote any unsigned integer type whose size is
811 // less than int to an int.
Mike Stump11289f42009-09-09 15:08:12 +0000812 (!FromType->isSignedIntegerType() &&
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000813 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000814 return To->getKind() == BuiltinType::Int;
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000815 }
816
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000817 return To->getKind() == BuiltinType::UInt;
818 }
819
820 // An rvalue of type wchar_t (3.9.1) or an enumeration type (7.2)
821 // can be converted to an rvalue of the first of the following types
822 // that can represent all the values of its underlying type: int,
823 // unsigned int, long, or unsigned long (C++ 4.5p2).
John McCall56774992009-12-09 09:09:27 +0000824
825 // We pre-calculate the promotion type for enum types.
826 if (const EnumType *FromEnumType = FromType->getAs<EnumType>())
827 if (ToType->isIntegerType())
828 return Context.hasSameUnqualifiedType(ToType,
829 FromEnumType->getDecl()->getPromotionType());
830
831 if (FromType->isWideCharType() && ToType->isIntegerType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000832 // Determine whether the type we're converting from is signed or
833 // unsigned.
834 bool FromIsSigned;
835 uint64_t FromSize = Context.getTypeSize(FromType);
John McCall56774992009-12-09 09:09:27 +0000836
837 // FIXME: Is wchar_t signed or unsigned? We assume it's signed for now.
838 FromIsSigned = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000839
840 // The types we'll try to promote to, in the appropriate
841 // order. Try each of these types.
Mike Stump11289f42009-09-09 15:08:12 +0000842 QualType PromoteTypes[6] = {
843 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregor1d248c52008-12-12 02:00:36 +0000844 Context.LongTy, Context.UnsignedLongTy ,
845 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000846 };
Douglas Gregor1d248c52008-12-12 02:00:36 +0000847 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000848 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
849 if (FromSize < ToSize ||
Mike Stump11289f42009-09-09 15:08:12 +0000850 (FromSize == ToSize &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000851 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
852 // We found the type that we can promote to. If this is the
853 // type we wanted, we have a promotion. Otherwise, no
854 // promotion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +0000855 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000856 }
857 }
858 }
859
860 // An rvalue for an integral bit-field (9.6) can be converted to an
861 // rvalue of type int if int can represent all the values of the
862 // bit-field; otherwise, it can be converted to unsigned int if
863 // unsigned int can represent all the values of the bit-field. If
864 // the bit-field is larger yet, no integral promotion applies to
865 // it. If the bit-field has an enumerated type, it is treated as any
866 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump87c57ac2009-05-16 07:39:55 +0000867 // FIXME: We should delay checking of bit-fields until we actually perform the
868 // conversion.
Douglas Gregor71235ec2009-05-02 02:18:30 +0000869 using llvm::APSInt;
870 if (From)
871 if (FieldDecl *MemberDecl = From->getBitField()) {
Douglas Gregor2eedc3a2008-12-20 23:49:58 +0000872 APSInt BitWidth;
Douglas Gregor71235ec2009-05-02 02:18:30 +0000873 if (FromType->isIntegralType() && !FromType->isEnumeralType() &&
874 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
875 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
876 ToSize = Context.getTypeSize(ToType);
Mike Stump11289f42009-09-09 15:08:12 +0000877
Douglas Gregor2eedc3a2008-12-20 23:49:58 +0000878 // Are we promoting to an int from a bitfield that fits in an int?
879 if (BitWidth < ToSize ||
880 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
881 return To->getKind() == BuiltinType::Int;
882 }
Mike Stump11289f42009-09-09 15:08:12 +0000883
Douglas Gregor2eedc3a2008-12-20 23:49:58 +0000884 // Are we promoting to an unsigned int from an unsigned bitfield
885 // that fits into an unsigned int?
886 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
887 return To->getKind() == BuiltinType::UInt;
888 }
Mike Stump11289f42009-09-09 15:08:12 +0000889
Douglas Gregor2eedc3a2008-12-20 23:49:58 +0000890 return false;
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000891 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000892 }
Mike Stump11289f42009-09-09 15:08:12 +0000893
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000894 // An rvalue of type bool can be converted to an rvalue of type int,
895 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000896 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000897 return true;
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000898 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000899
900 return false;
901}
902
903/// IsFloatingPointPromotion - Determines whether the conversion from
904/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
905/// returns true and sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +0000906bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000907 /// An rvalue of type float can be converted to an rvalue of type
908 /// double. (C++ 4.6p1).
John McCall9dd450b2009-09-21 23:43:11 +0000909 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
910 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000911 if (FromBuiltin->getKind() == BuiltinType::Float &&
912 ToBuiltin->getKind() == BuiltinType::Double)
913 return true;
914
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000915 // C99 6.3.1.5p1:
916 // When a float is promoted to double or long double, or a
917 // double is promoted to long double [...].
918 if (!getLangOptions().CPlusPlus &&
919 (FromBuiltin->getKind() == BuiltinType::Float ||
920 FromBuiltin->getKind() == BuiltinType::Double) &&
921 (ToBuiltin->getKind() == BuiltinType::LongDouble))
922 return true;
923 }
924
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000925 return false;
926}
927
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000928/// \brief Determine if a conversion is a complex promotion.
929///
930/// A complex promotion is defined as a complex -> complex conversion
931/// where the conversion between the underlying real types is a
Douglas Gregor67525022009-02-12 00:26:06 +0000932/// floating-point or integral promotion.
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000933bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +0000934 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000935 if (!FromComplex)
936 return false;
937
John McCall9dd450b2009-09-21 23:43:11 +0000938 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000939 if (!ToComplex)
940 return false;
941
942 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +0000943 ToComplex->getElementType()) ||
944 IsIntegralPromotion(0, FromComplex->getElementType(),
945 ToComplex->getElementType());
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000946}
947
Douglas Gregor237f96c2008-11-26 23:31:11 +0000948/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
949/// the pointer type FromPtr to a pointer to type ToPointee, with the
950/// same type qualifiers as FromPtr has on its pointee type. ToType,
951/// if non-empty, will be a pointer to ToType that may or may not have
952/// the right set of qualifiers on its pointee.
Mike Stump11289f42009-09-09 15:08:12 +0000953static QualType
954BuildSimilarlyQualifiedPointerType(const PointerType *FromPtr,
Douglas Gregor237f96c2008-11-26 23:31:11 +0000955 QualType ToPointee, QualType ToType,
956 ASTContext &Context) {
957 QualType CanonFromPointee = Context.getCanonicalType(FromPtr->getPointeeType());
958 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall8ccfcb52009-09-24 19:53:00 +0000959 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump11289f42009-09-09 15:08:12 +0000960
961 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +0000962 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregor237f96c2008-11-26 23:31:11 +0000963 // ToType is exactly what we need. Return it.
John McCall8ccfcb52009-09-24 19:53:00 +0000964 if (!ToType.isNull())
Douglas Gregor237f96c2008-11-26 23:31:11 +0000965 return ToType;
966
967 // Build a pointer to ToPointee. It has the right qualifiers
968 // already.
969 return Context.getPointerType(ToPointee);
970 }
971
972 // Just build a canonical type that has the right qualifiers.
John McCall8ccfcb52009-09-24 19:53:00 +0000973 return Context.getPointerType(
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +0000974 Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(),
975 Quals));
Douglas Gregor237f96c2008-11-26 23:31:11 +0000976}
977
Fariborz Jahanian01cbe442009-12-16 23:13:33 +0000978/// BuildSimilarlyQualifiedObjCObjectPointerType - In a pointer conversion from
979/// the FromType, which is an objective-c pointer, to ToType, which may or may
980/// not have the right set of qualifiers.
981static QualType
982BuildSimilarlyQualifiedObjCObjectPointerType(QualType FromType,
983 QualType ToType,
984 ASTContext &Context) {
985 QualType CanonFromType = Context.getCanonicalType(FromType);
986 QualType CanonToType = Context.getCanonicalType(ToType);
987 Qualifiers Quals = CanonFromType.getQualifiers();
988
989 // Exact qualifier match -> return the pointer type we're converting to.
990 if (CanonToType.getLocalQualifiers() == Quals)
991 return ToType;
992
993 // Just build a canonical type that has the right qualifiers.
994 return Context.getQualifiedType(CanonToType.getLocalUnqualifiedType(), Quals);
995}
996
Mike Stump11289f42009-09-09 15:08:12 +0000997static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlsson759b7892009-08-28 15:55:56 +0000998 bool InOverloadResolution,
999 ASTContext &Context) {
1000 // Handle value-dependent integral null pointer constants correctly.
1001 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
1002 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
1003 Expr->getType()->isIntegralType())
1004 return !InOverloadResolution;
1005
Douglas Gregor56751b52009-09-25 04:25:58 +00001006 return Expr->isNullPointerConstant(Context,
1007 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1008 : Expr::NPC_ValueDependentIsNull);
Anders Carlsson759b7892009-08-28 15:55:56 +00001009}
Mike Stump11289f42009-09-09 15:08:12 +00001010
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001011/// IsPointerConversion - Determines whether the conversion of the
1012/// expression From, which has the (possibly adjusted) type FromType,
1013/// can be converted to the type ToType via a pointer conversion (C++
1014/// 4.10). If so, returns true and places the converted type (that
1015/// might differ from ToType in its cv-qualifiers at some level) into
1016/// ConvertedType.
Douglas Gregor231d1c62008-11-27 00:15:41 +00001017///
Douglas Gregora29dc052008-11-27 01:19:21 +00001018/// This routine also supports conversions to and from block pointers
1019/// and conversions with Objective-C's 'id', 'id<protocols...>', and
1020/// pointers to interfaces. FIXME: Once we've determined the
1021/// appropriate overloading rules for Objective-C, we may want to
1022/// split the Objective-C checks into a different routine; however,
1023/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor47d3f272008-12-19 17:40:08 +00001024/// conversions, so for now they live here. IncompatibleObjC will be
1025/// set if the conversion is an allowed Objective-C conversion that
1026/// should result in a warning.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001027bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +00001028 bool InOverloadResolution,
Douglas Gregor47d3f272008-12-19 17:40:08 +00001029 QualType& ConvertedType,
Mike Stump11289f42009-09-09 15:08:12 +00001030 bool &IncompatibleObjC) {
Douglas Gregor47d3f272008-12-19 17:40:08 +00001031 IncompatibleObjC = false;
Douglas Gregora119f102008-12-19 19:13:09 +00001032 if (isObjCPointerConversion(FromType, ToType, ConvertedType, IncompatibleObjC))
1033 return true;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001034
Mike Stump11289f42009-09-09 15:08:12 +00001035 // Conversion from a null pointer constant to any Objective-C pointer type.
1036 if (ToType->isObjCObjectPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001037 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor79a6b012008-12-22 20:51:52 +00001038 ConvertedType = ToType;
1039 return true;
1040 }
1041
Douglas Gregor231d1c62008-11-27 00:15:41 +00001042 // Blocks: Block pointers can be converted to void*.
1043 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001044 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00001045 ConvertedType = ToType;
1046 return true;
1047 }
1048 // Blocks: A null pointer constant can be converted to a block
1049 // pointer type.
Mike Stump11289f42009-09-09 15:08:12 +00001050 if (ToType->isBlockPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001051 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00001052 ConvertedType = ToType;
1053 return true;
1054 }
1055
Sebastian Redl576fd422009-05-10 18:38:11 +00001056 // If the left-hand-side is nullptr_t, the right side can be a null
1057 // pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00001058 if (ToType->isNullPtrType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001059 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl576fd422009-05-10 18:38:11 +00001060 ConvertedType = ToType;
1061 return true;
1062 }
1063
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001064 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001065 if (!ToTypePtr)
1066 return false;
1067
1068 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlsson759b7892009-08-28 15:55:56 +00001069 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001070 ConvertedType = ToType;
1071 return true;
1072 }
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001073
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001074 // Beyond this point, both types need to be pointers
1075 // , including objective-c pointers.
1076 QualType ToPointeeType = ToTypePtr->getPointeeType();
1077 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType()) {
1078 ConvertedType = BuildSimilarlyQualifiedObjCObjectPointerType(FromType,
1079 ToType, Context);
1080 return true;
1081
1082 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001083 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001084 if (!FromTypePtr)
1085 return false;
1086
1087 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001088
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001089 // An rvalue of type "pointer to cv T," where T is an object type,
1090 // can be converted to an rvalue of type "pointer to cv void" (C++
1091 // 4.10p2).
Douglas Gregor64259f52009-03-24 20:32:41 +00001092 if (FromPointeeType->isObjectType() && ToPointeeType->isVoidType()) {
Mike Stump11289f42009-09-09 15:08:12 +00001093 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00001094 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001095 ToType, Context);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001096 return true;
1097 }
1098
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001099 // When we're overloading in C, we allow a special kind of pointer
1100 // conversion for compatible-but-not-identical pointee types.
Mike Stump11289f42009-09-09 15:08:12 +00001101 if (!getLangOptions().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001102 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001103 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001104 ToPointeeType,
Mike Stump11289f42009-09-09 15:08:12 +00001105 ToType, Context);
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001106 return true;
1107 }
1108
Douglas Gregor5c407d92008-10-23 00:40:37 +00001109 // C++ [conv.ptr]p3:
Mike Stump11289f42009-09-09 15:08:12 +00001110 //
Douglas Gregor5c407d92008-10-23 00:40:37 +00001111 // An rvalue of type "pointer to cv D," where D is a class type,
1112 // can be converted to an rvalue of type "pointer to cv B," where
1113 // B is a base class (clause 10) of D. If B is an inaccessible
1114 // (clause 11) or ambiguous (10.2) base class of D, a program that
1115 // necessitates this conversion is ill-formed. The result of the
1116 // conversion is a pointer to the base class sub-object of the
1117 // derived class object. The null pointer value is converted to
1118 // the null pointer value of the destination type.
1119 //
Douglas Gregor39c16d42008-10-24 04:54:22 +00001120 // Note that we do not check for ambiguity or inaccessibility
1121 // here. That is handled by CheckPointerConversion.
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001122 if (getLangOptions().CPlusPlus &&
1123 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregord28f0412010-02-22 17:06:41 +00001124 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
Douglas Gregore6fb91f2009-10-29 23:08:22 +00001125 !RequireCompleteType(From->getLocStart(), FromPointeeType, PDiag()) &&
Douglas Gregor237f96c2008-11-26 23:31:11 +00001126 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001127 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00001128 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001129 ToType, Context);
1130 return true;
1131 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00001132
Douglas Gregora119f102008-12-19 19:13:09 +00001133 return false;
1134}
1135
1136/// isObjCPointerConversion - Determines whether this is an
1137/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
1138/// with the same arguments and return values.
Mike Stump11289f42009-09-09 15:08:12 +00001139bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregora119f102008-12-19 19:13:09 +00001140 QualType& ConvertedType,
1141 bool &IncompatibleObjC) {
1142 if (!getLangOptions().ObjC1)
1143 return false;
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00001144
Steve Naroff7cae42b2009-07-10 23:34:53 +00001145 // First, we handle all conversions on ObjC object pointer types.
John McCall9dd450b2009-09-21 23:43:11 +00001146 const ObjCObjectPointerType* ToObjCPtr = ToType->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00001147 const ObjCObjectPointerType *FromObjCPtr =
John McCall9dd450b2009-09-21 23:43:11 +00001148 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregora119f102008-12-19 19:13:09 +00001149
Steve Naroff7cae42b2009-07-10 23:34:53 +00001150 if (ToObjCPtr && FromObjCPtr) {
Steve Naroff1329fa02009-07-15 18:40:39 +00001151 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff7cae42b2009-07-10 23:34:53 +00001152 // pointer to any interface (in both directions).
Steve Naroff1329fa02009-07-15 18:40:39 +00001153 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001154 ConvertedType = ToType;
1155 return true;
1156 }
1157 // Conversions with Objective-C's id<...>.
Mike Stump11289f42009-09-09 15:08:12 +00001158 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff7cae42b2009-07-10 23:34:53 +00001159 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump11289f42009-09-09 15:08:12 +00001160 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff8e6aee52009-07-23 01:01:38 +00001161 /*compare=*/false)) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001162 ConvertedType = ToType;
1163 return true;
1164 }
1165 // Objective C++: We're able to convert from a pointer to an
1166 // interface to a pointer to a different interface.
1167 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
Fariborz Jahanianb397e432010-03-15 18:36:00 +00001168 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
1169 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
1170 if (getLangOptions().CPlusPlus && LHS && RHS &&
1171 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
1172 FromObjCPtr->getPointeeType()))
1173 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00001174 ConvertedType = ToType;
1175 return true;
1176 }
1177
1178 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
1179 // Okay: this is some kind of implicit downcast of Objective-C
1180 // interfaces, which is permitted. However, we're going to
1181 // complain about it.
1182 IncompatibleObjC = true;
1183 ConvertedType = FromType;
1184 return true;
1185 }
Mike Stump11289f42009-09-09 15:08:12 +00001186 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00001187 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor033f56d2008-12-23 00:53:59 +00001188 QualType ToPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001189 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001190 ToPointeeType = ToCPtr->getPointeeType();
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001191 else if (const BlockPointerType *ToBlockPtr =
1192 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian879cc732010-01-21 00:08:17 +00001193 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001194 // to a block pointer type.
1195 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
1196 ConvertedType = ToType;
1197 return true;
1198 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00001199 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001200 }
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00001201 else if (FromType->getAs<BlockPointerType>() &&
1202 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
1203 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian879cc732010-01-21 00:08:17 +00001204 // pointer to any object.
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00001205 ConvertedType = ToType;
1206 return true;
1207 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00001208 else
Douglas Gregora119f102008-12-19 19:13:09 +00001209 return false;
1210
Douglas Gregor033f56d2008-12-23 00:53:59 +00001211 QualType FromPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001212 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001213 FromPointeeType = FromCPtr->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001214 else if (const BlockPointerType *FromBlockPtr = FromType->getAs<BlockPointerType>())
Douglas Gregor033f56d2008-12-23 00:53:59 +00001215 FromPointeeType = FromBlockPtr->getPointeeType();
1216 else
Douglas Gregora119f102008-12-19 19:13:09 +00001217 return false;
1218
Douglas Gregora119f102008-12-19 19:13:09 +00001219 // If we have pointers to pointers, recursively check whether this
1220 // is an Objective-C conversion.
1221 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
1222 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1223 IncompatibleObjC)) {
1224 // We always complain about this conversion.
1225 IncompatibleObjC = true;
1226 ConvertedType = ToType;
1227 return true;
1228 }
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00001229 // Allow conversion of pointee being objective-c pointer to another one;
1230 // as in I* to id.
1231 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
1232 ToPointeeType->getAs<ObjCObjectPointerType>() &&
1233 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1234 IncompatibleObjC)) {
1235 ConvertedType = ToType;
1236 return true;
1237 }
1238
Douglas Gregor033f56d2008-12-23 00:53:59 +00001239 // If we have pointers to functions or blocks, check whether the only
Douglas Gregora119f102008-12-19 19:13:09 +00001240 // differences in the argument and result types are in Objective-C
1241 // pointer conversions. If so, we permit the conversion (but
1242 // complain about it).
Mike Stump11289f42009-09-09 15:08:12 +00001243 const FunctionProtoType *FromFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00001244 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001245 const FunctionProtoType *ToFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00001246 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregora119f102008-12-19 19:13:09 +00001247 if (FromFunctionType && ToFunctionType) {
1248 // If the function types are exactly the same, this isn't an
1249 // Objective-C pointer conversion.
1250 if (Context.getCanonicalType(FromPointeeType)
1251 == Context.getCanonicalType(ToPointeeType))
1252 return false;
1253
1254 // Perform the quick checks that will tell us whether these
1255 // function types are obviously different.
1256 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
1257 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
1258 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
1259 return false;
1260
1261 bool HasObjCConversion = false;
1262 if (Context.getCanonicalType(FromFunctionType->getResultType())
1263 == Context.getCanonicalType(ToFunctionType->getResultType())) {
1264 // Okay, the types match exactly. Nothing to do.
1265 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
1266 ToFunctionType->getResultType(),
1267 ConvertedType, IncompatibleObjC)) {
1268 // Okay, we have an Objective-C pointer conversion.
1269 HasObjCConversion = true;
1270 } else {
1271 // Function types are too different. Abort.
1272 return false;
1273 }
Mike Stump11289f42009-09-09 15:08:12 +00001274
Douglas Gregora119f102008-12-19 19:13:09 +00001275 // Check argument types.
1276 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
1277 ArgIdx != NumArgs; ++ArgIdx) {
1278 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
1279 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
1280 if (Context.getCanonicalType(FromArgType)
1281 == Context.getCanonicalType(ToArgType)) {
1282 // Okay, the types match exactly. Nothing to do.
1283 } else if (isObjCPointerConversion(FromArgType, ToArgType,
1284 ConvertedType, IncompatibleObjC)) {
1285 // Okay, we have an Objective-C pointer conversion.
1286 HasObjCConversion = true;
1287 } else {
1288 // Argument types are too different. Abort.
1289 return false;
1290 }
1291 }
1292
1293 if (HasObjCConversion) {
1294 // We had an Objective-C conversion. Allow this pointer
1295 // conversion, but complain about it.
1296 ConvertedType = ToType;
1297 IncompatibleObjC = true;
1298 return true;
1299 }
1300 }
1301
Sebastian Redl72b597d2009-01-25 19:43:20 +00001302 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001303}
1304
Douglas Gregor39c16d42008-10-24 04:54:22 +00001305/// CheckPointerConversion - Check the pointer conversion from the
1306/// expression From to the type ToType. This routine checks for
Sebastian Redl9f831db2009-07-25 15:41:38 +00001307/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor39c16d42008-10-24 04:54:22 +00001308/// conversions for which IsPointerConversion has already returned
1309/// true. It returns true and produces a diagnostic if there was an
1310/// error, or returns false otherwise.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001311bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
Sebastian Redl7c353682009-11-14 21:15:49 +00001312 CastExpr::CastKind &Kind,
1313 bool IgnoreBaseAccess) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001314 QualType FromType = From->getType();
1315
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001316 if (const PointerType *FromPtrType = FromType->getAs<PointerType>())
1317 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001318 QualType FromPointeeType = FromPtrType->getPointeeType(),
1319 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregor1e57a3f2008-12-18 23:43:31 +00001320
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001321 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
1322 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001323 // We must have a derived-to-base conversion. Check an
1324 // ambiguous or inaccessible conversion.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001325 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
1326 From->getExprLoc(),
Sebastian Redl7c353682009-11-14 21:15:49 +00001327 From->getSourceRange(),
1328 IgnoreBaseAccess))
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001329 return true;
1330
1331 // The conversion was successful.
1332 Kind = CastExpr::CK_DerivedToBase;
Douglas Gregor39c16d42008-10-24 04:54:22 +00001333 }
1334 }
Mike Stump11289f42009-09-09 15:08:12 +00001335 if (const ObjCObjectPointerType *FromPtrType =
John McCall9dd450b2009-09-21 23:43:11 +00001336 FromType->getAs<ObjCObjectPointerType>())
Mike Stump11289f42009-09-09 15:08:12 +00001337 if (const ObjCObjectPointerType *ToPtrType =
John McCall9dd450b2009-09-21 23:43:11 +00001338 ToType->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001339 // Objective-C++ conversions are always okay.
1340 // FIXME: We should have a different class of conversions for the
1341 // Objective-C++ implicit conversions.
Steve Naroff1329fa02009-07-15 18:40:39 +00001342 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001343 return false;
Douglas Gregor39c16d42008-10-24 04:54:22 +00001344
Steve Naroff7cae42b2009-07-10 23:34:53 +00001345 }
Douglas Gregor39c16d42008-10-24 04:54:22 +00001346 return false;
1347}
1348
Sebastian Redl72b597d2009-01-25 19:43:20 +00001349/// IsMemberPointerConversion - Determines whether the conversion of the
1350/// expression From, which has the (possibly adjusted) type FromType, can be
1351/// converted to the type ToType via a member pointer conversion (C++ 4.11).
1352/// If so, returns true and places the converted type (that might differ from
1353/// ToType in its cv-qualifiers at some level) into ConvertedType.
1354bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
Douglas Gregor56751b52009-09-25 04:25:58 +00001355 QualType ToType,
1356 bool InOverloadResolution,
1357 QualType &ConvertedType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001358 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00001359 if (!ToTypePtr)
1360 return false;
1361
1362 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregor56751b52009-09-25 04:25:58 +00001363 if (From->isNullPointerConstant(Context,
1364 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1365 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00001366 ConvertedType = ToType;
1367 return true;
1368 }
1369
1370 // Otherwise, both types have to be member pointers.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001371 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00001372 if (!FromTypePtr)
1373 return false;
1374
1375 // A pointer to member of B can be converted to a pointer to member of D,
1376 // where D is derived from B (C++ 4.11p2).
1377 QualType FromClass(FromTypePtr->getClass(), 0);
1378 QualType ToClass(ToTypePtr->getClass(), 0);
1379 // FIXME: What happens when these are dependent? Is this function even called?
1380
1381 if (IsDerivedFrom(ToClass, FromClass)) {
1382 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
1383 ToClass.getTypePtr());
1384 return true;
1385 }
1386
1387 return false;
1388}
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001389
Sebastian Redl72b597d2009-01-25 19:43:20 +00001390/// CheckMemberPointerConversion - Check the member pointer conversion from the
1391/// expression From to the type ToType. This routine checks for ambiguous or
John McCall5b0829a2010-02-10 09:31:12 +00001392/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl72b597d2009-01-25 19:43:20 +00001393/// for which IsMemberPointerConversion has already returned true. It returns
1394/// true and produces a diagnostic if there was an error, or returns false
1395/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00001396bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
Sebastian Redl7c353682009-11-14 21:15:49 +00001397 CastExpr::CastKind &Kind,
1398 bool IgnoreBaseAccess) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00001399 QualType FromType = From->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001400 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlssond7923c62009-08-22 23:33:40 +00001401 if (!FromPtrType) {
1402 // This must be a null pointer to member pointer conversion
Douglas Gregor56751b52009-09-25 04:25:58 +00001403 assert(From->isNullPointerConstant(Context,
1404 Expr::NPC_ValueDependentIsNull) &&
Anders Carlssond7923c62009-08-22 23:33:40 +00001405 "Expr must be null pointer constant!");
1406 Kind = CastExpr::CK_NullToMemberPointer;
Sebastian Redled8f2002009-01-28 18:33:18 +00001407 return false;
Anders Carlssond7923c62009-08-22 23:33:40 +00001408 }
Sebastian Redl72b597d2009-01-25 19:43:20 +00001409
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001410 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redled8f2002009-01-28 18:33:18 +00001411 assert(ToPtrType && "No member pointer cast has a target type "
1412 "that is not a member pointer.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00001413
Sebastian Redled8f2002009-01-28 18:33:18 +00001414 QualType FromClass = QualType(FromPtrType->getClass(), 0);
1415 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00001416
Sebastian Redled8f2002009-01-28 18:33:18 +00001417 // FIXME: What about dependent types?
1418 assert(FromClass->isRecordType() && "Pointer into non-class.");
1419 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00001420
John McCall5b0829a2010-02-10 09:31:12 +00001421 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/ true,
Douglas Gregor36d1b142009-10-06 17:59:45 +00001422 /*DetectVirtual=*/true);
Sebastian Redled8f2002009-01-28 18:33:18 +00001423 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1424 assert(DerivationOkay &&
1425 "Should not have been called if derivation isn't OK.");
1426 (void)DerivationOkay;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001427
Sebastian Redled8f2002009-01-28 18:33:18 +00001428 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
1429 getUnqualifiedType())) {
Sebastian Redled8f2002009-01-28 18:33:18 +00001430 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1431 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
1432 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
1433 return true;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001434 }
Sebastian Redled8f2002009-01-28 18:33:18 +00001435
Douglas Gregor89ee6822009-02-28 01:32:25 +00001436 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redled8f2002009-01-28 18:33:18 +00001437 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
1438 << FromClass << ToClass << QualType(VBase, 0)
1439 << From->getSourceRange();
1440 return true;
1441 }
1442
John McCall5b0829a2010-02-10 09:31:12 +00001443 if (!IgnoreBaseAccess)
John McCall1064d7e2010-03-16 05:22:47 +00001444 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
1445 Paths.front(),
1446 diag::err_downcast_from_inaccessible_base);
John McCall5b0829a2010-02-10 09:31:12 +00001447
Anders Carlssond7923c62009-08-22 23:33:40 +00001448 // Must be a base to derived member conversion.
1449 Kind = CastExpr::CK_BaseToDerivedMemberPointer;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001450 return false;
1451}
1452
Douglas Gregor9a657932008-10-21 23:43:52 +00001453/// IsQualificationConversion - Determines whether the conversion from
1454/// an rvalue of type FromType to ToType is a qualification conversion
1455/// (C++ 4.4).
Mike Stump11289f42009-09-09 15:08:12 +00001456bool
1457Sema::IsQualificationConversion(QualType FromType, QualType ToType) {
Douglas Gregor9a657932008-10-21 23:43:52 +00001458 FromType = Context.getCanonicalType(FromType);
1459 ToType = Context.getCanonicalType(ToType);
1460
1461 // If FromType and ToType are the same type, this is not a
1462 // qualification conversion.
Sebastian Redlcbdffb12010-02-03 19:36:07 +00001463 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor9a657932008-10-21 23:43:52 +00001464 return false;
Sebastian Redled8f2002009-01-28 18:33:18 +00001465
Douglas Gregor9a657932008-10-21 23:43:52 +00001466 // (C++ 4.4p4):
1467 // A conversion can add cv-qualifiers at levels other than the first
1468 // in multi-level pointers, subject to the following rules: [...]
1469 bool PreviousToQualsIncludeConst = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00001470 bool UnwrappedAnyPointer = false;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001471 while (UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor9a657932008-10-21 23:43:52 +00001472 // Within each iteration of the loop, we check the qualifiers to
1473 // determine if this still looks like a qualification
1474 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00001475 // pointers or pointers-to-members and do it all again
Douglas Gregor9a657932008-10-21 23:43:52 +00001476 // until there are no more pointers or pointers-to-members left to
1477 // unwrap.
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001478 UnwrappedAnyPointer = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00001479
1480 // -- for every j > 0, if const is in cv 1,j then const is in cv
1481 // 2,j, and similarly for volatile.
Douglas Gregorea2d4212008-10-22 00:38:21 +00001482 if (!ToType.isAtLeastAsQualifiedAs(FromType))
Douglas Gregor9a657932008-10-21 23:43:52 +00001483 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001484
Douglas Gregor9a657932008-10-21 23:43:52 +00001485 // -- if the cv 1,j and cv 2,j are different, then const is in
1486 // every cv for 0 < k < j.
1487 if (FromType.getCVRQualifiers() != ToType.getCVRQualifiers()
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001488 && !PreviousToQualsIncludeConst)
Douglas Gregor9a657932008-10-21 23:43:52 +00001489 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001490
Douglas Gregor9a657932008-10-21 23:43:52 +00001491 // Keep track of whether all prior cv-qualifiers in the "to" type
1492 // include const.
Mike Stump11289f42009-09-09 15:08:12 +00001493 PreviousToQualsIncludeConst
Douglas Gregor9a657932008-10-21 23:43:52 +00001494 = PreviousToQualsIncludeConst && ToType.isConstQualified();
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001495 }
Douglas Gregor9a657932008-10-21 23:43:52 +00001496
1497 // We are left with FromType and ToType being the pointee types
1498 // after unwrapping the original FromType and ToType the same number
1499 // of types. If we unwrapped any pointers, and if FromType and
1500 // ToType have the same unqualified type (since we checked
1501 // qualifiers above), then this is a qualification conversion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001502 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor9a657932008-10-21 23:43:52 +00001503}
1504
Douglas Gregor576e98c2009-01-30 23:27:23 +00001505/// Determines whether there is a user-defined conversion sequence
1506/// (C++ [over.ics.user]) that converts expression From to the type
1507/// ToType. If such a conversion exists, User will contain the
1508/// user-defined conversion sequence that performs such a conversion
1509/// and this routine will return true. Otherwise, this routine returns
1510/// false and User is unspecified.
1511///
1512/// \param AllowConversionFunctions true if the conversion should
1513/// consider conversion functions at all. If false, only constructors
1514/// will be considered.
1515///
1516/// \param AllowExplicit true if the conversion should consider C++0x
1517/// "explicit" conversion functions as well as non-explicit conversion
1518/// functions (C++0x [class.conv.fct]p2).
Sebastian Redl42e92c42009-04-12 17:16:29 +00001519///
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00001520/// \param UserCast true if looking for user defined conversion for a static
1521/// cast.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001522OverloadingResult Sema::IsUserDefinedConversion(Expr *From, QualType ToType,
1523 UserDefinedConversionSequence& User,
1524 OverloadCandidateSet& CandidateSet,
1525 bool AllowConversionFunctions,
1526 bool AllowExplicit,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001527 bool UserCast) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001528 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00001529 if (RequireCompleteType(From->getLocStart(), ToType, PDiag())) {
1530 // We're not going to find any constructors.
1531 } else if (CXXRecordDecl *ToRecordDecl
1532 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Douglas Gregor89ee6822009-02-28 01:32:25 +00001533 // C++ [over.match.ctor]p1:
1534 // When objects of class type are direct-initialized (8.5), or
1535 // copy-initialized from an expression of the same or a
1536 // derived class type (8.5), overload resolution selects the
1537 // constructor. [...] For copy-initialization, the candidate
1538 // functions are all the converting constructors (12.3.1) of
1539 // that class. The argument list is the expression-list within
1540 // the parentheses of the initializer.
Douglas Gregor379d84b2009-11-13 18:44:21 +00001541 bool SuppressUserConversions = !UserCast;
1542 if (Context.hasSameUnqualifiedType(ToType, From->getType()) ||
1543 IsDerivedFrom(From->getType(), ToType)) {
1544 SuppressUserConversions = false;
1545 AllowConversionFunctions = false;
1546 }
1547
Mike Stump11289f42009-09-09 15:08:12 +00001548 DeclarationName ConstructorName
Douglas Gregor89ee6822009-02-28 01:32:25 +00001549 = Context.DeclarationNames.getCXXConstructorName(
1550 Context.getCanonicalType(ToType).getUnqualifiedType());
1551 DeclContext::lookup_iterator Con, ConEnd;
Mike Stump11289f42009-09-09 15:08:12 +00001552 for (llvm::tie(Con, ConEnd)
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001553 = ToRecordDecl->lookup(ConstructorName);
Douglas Gregor89ee6822009-02-28 01:32:25 +00001554 Con != ConEnd; ++Con) {
John McCalla0296f72010-03-19 07:35:19 +00001555 NamedDecl *D = *Con;
1556 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
1557
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001558 // Find the constructor (which may be a template).
1559 CXXConstructorDecl *Constructor = 0;
1560 FunctionTemplateDecl *ConstructorTmpl
John McCalla0296f72010-03-19 07:35:19 +00001561 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001562 if (ConstructorTmpl)
Mike Stump11289f42009-09-09 15:08:12 +00001563 Constructor
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001564 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
1565 else
John McCalla0296f72010-03-19 07:35:19 +00001566 Constructor = cast<CXXConstructorDecl>(D);
Douglas Gregorffe14e32009-11-14 01:20:54 +00001567
Fariborz Jahanian11a8e952009-08-06 17:22:51 +00001568 if (!Constructor->isInvalidDecl() &&
Anders Carlssond20e7952009-08-28 16:57:08 +00001569 Constructor->isConvertingConstructor(AllowExplicit)) {
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001570 if (ConstructorTmpl)
John McCalla0296f72010-03-19 07:35:19 +00001571 AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00001572 /*ExplicitArgs*/ 0,
John McCall6b51f282009-11-23 01:53:49 +00001573 &From, 1, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00001574 SuppressUserConversions);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001575 else
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00001576 // Allow one user-defined conversion when user specifies a
1577 // From->ToType conversion via an static cast (c-style, etc).
John McCalla0296f72010-03-19 07:35:19 +00001578 AddOverloadCandidate(Constructor, FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00001579 &From, 1, CandidateSet,
Douglas Gregorb05275a2010-04-16 17:41:49 +00001580 SuppressUserConversions);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001581 }
Douglas Gregor89ee6822009-02-28 01:32:25 +00001582 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001583 }
1584 }
1585
Douglas Gregor576e98c2009-01-30 23:27:23 +00001586 if (!AllowConversionFunctions) {
1587 // Don't allow any conversion functions to enter the overload set.
Mike Stump11289f42009-09-09 15:08:12 +00001588 } else if (RequireCompleteType(From->getLocStart(), From->getType(),
1589 PDiag(0)
Anders Carlssond624e162009-08-26 23:45:07 +00001590 << From->getSourceRange())) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00001591 // No conversion functions from incomplete types.
Mike Stump11289f42009-09-09 15:08:12 +00001592 } else if (const RecordType *FromRecordType
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001593 = From->getType()->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00001594 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001595 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
1596 // Add all of the conversion functions as candidates.
John McCallad371252010-01-20 00:46:10 +00001597 const UnresolvedSetImpl *Conversions
Fariborz Jahanianf4061e32009-09-14 20:41:01 +00001598 = FromRecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00001599 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00001600 E = Conversions->end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00001601 DeclAccessPair FoundDecl = I.getPair();
1602 NamedDecl *D = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00001603 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
1604 if (isa<UsingShadowDecl>(D))
1605 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1606
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001607 CXXConversionDecl *Conv;
1608 FunctionTemplateDecl *ConvTemplate;
John McCallda4458e2010-03-31 01:36:47 +00001609 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
1610 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001611 else
John McCallda4458e2010-03-31 01:36:47 +00001612 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001613
1614 if (AllowExplicit || !Conv->isExplicit()) {
1615 if (ConvTemplate)
John McCalla0296f72010-03-19 07:35:19 +00001616 AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00001617 ActingContext, From, ToType,
1618 CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001619 else
John McCalla0296f72010-03-19 07:35:19 +00001620 AddConversionCandidate(Conv, FoundDecl, ActingContext,
John McCallb89836b2010-01-26 01:37:31 +00001621 From, ToType, CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001622 }
1623 }
1624 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00001625 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001626
1627 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00001628 switch (BestViableFunction(CandidateSet, From->getLocStart(), Best)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001629 case OR_Success:
1630 // Record the standard conversion we used and the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +00001631 if (CXXConstructorDecl *Constructor
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001632 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
1633 // C++ [over.ics.user]p1:
1634 // If the user-defined conversion is specified by a
1635 // constructor (12.3.1), the initial standard conversion
1636 // sequence converts the source type to the type required by
1637 // the argument of the constructor.
1638 //
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001639 QualType ThisType = Constructor->getThisType(Context);
John McCall0d1da222010-01-12 00:44:57 +00001640 if (Best->Conversions[0].isEllipsis())
Fariborz Jahanian55824512009-11-06 00:23:08 +00001641 User.EllipsisConversion = true;
1642 else {
1643 User.Before = Best->Conversions[0].Standard;
1644 User.EllipsisConversion = false;
1645 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001646 User.ConversionFunction = Constructor;
1647 User.After.setAsIdentityConversion();
John McCall0d1da222010-01-12 00:44:57 +00001648 User.After.setFromType(
1649 ThisType->getAs<PointerType>()->getPointeeType());
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001650 User.After.setAllToTypes(ToType);
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001651 return OR_Success;
Douglas Gregora1f013e2008-11-07 22:36:19 +00001652 } else if (CXXConversionDecl *Conversion
1653 = dyn_cast<CXXConversionDecl>(Best->Function)) {
1654 // C++ [over.ics.user]p1:
1655 //
1656 // [...] If the user-defined conversion is specified by a
1657 // conversion function (12.3.2), the initial standard
1658 // conversion sequence converts the source type to the
1659 // implicit object parameter of the conversion function.
1660 User.Before = Best->Conversions[0].Standard;
1661 User.ConversionFunction = Conversion;
Fariborz Jahanian55824512009-11-06 00:23:08 +00001662 User.EllipsisConversion = false;
Mike Stump11289f42009-09-09 15:08:12 +00001663
1664 // C++ [over.ics.user]p2:
Douglas Gregora1f013e2008-11-07 22:36:19 +00001665 // The second standard conversion sequence converts the
1666 // result of the user-defined conversion to the target type
1667 // for the sequence. Since an implicit conversion sequence
1668 // is an initialization, the special rules for
1669 // initialization by user-defined conversion apply when
1670 // selecting the best user-defined conversion for a
1671 // user-defined conversion sequence (see 13.3.3 and
1672 // 13.3.3.1).
1673 User.After = Best->FinalConversion;
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001674 return OR_Success;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001675 } else {
Douglas Gregora1f013e2008-11-07 22:36:19 +00001676 assert(false && "Not a constructor or conversion function?");
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001677 return OR_No_Viable_Function;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001678 }
Mike Stump11289f42009-09-09 15:08:12 +00001679
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001680 case OR_No_Viable_Function:
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001681 return OR_No_Viable_Function;
Douglas Gregor171c45a2009-02-18 21:56:37 +00001682 case OR_Deleted:
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001683 // No conversion here! We're done.
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001684 return OR_Deleted;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001685
1686 case OR_Ambiguous:
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001687 return OR_Ambiguous;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001688 }
1689
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001690 return OR_No_Viable_Function;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001691}
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00001692
1693bool
Fariborz Jahanian76197412009-11-18 18:26:29 +00001694Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00001695 ImplicitConversionSequence ICS;
John McCallbc077cf2010-02-08 23:07:23 +00001696 OverloadCandidateSet CandidateSet(From->getExprLoc());
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00001697 OverloadingResult OvResult =
1698 IsUserDefinedConversion(From, ToType, ICS.UserDefined,
Douglas Gregor7b23e412010-04-16 17:25:05 +00001699 CandidateSet, true, false, false);
Fariborz Jahanian76197412009-11-18 18:26:29 +00001700 if (OvResult == OR_Ambiguous)
1701 Diag(From->getSourceRange().getBegin(),
1702 diag::err_typecheck_ambiguous_condition)
1703 << From->getType() << ToType << From->getSourceRange();
1704 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
1705 Diag(From->getSourceRange().getBegin(),
1706 diag::err_typecheck_nonviable_condition)
1707 << From->getType() << ToType << From->getSourceRange();
1708 else
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00001709 return false;
John McCallad907772010-01-12 07:18:19 +00001710 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, &From, 1);
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00001711 return true;
1712}
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001713
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001714/// CompareImplicitConversionSequences - Compare two implicit
1715/// conversion sequences to determine whether one is better than the
1716/// other or if they are indistinguishable (C++ 13.3.3.2).
Mike Stump11289f42009-09-09 15:08:12 +00001717ImplicitConversionSequence::CompareKind
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001718Sema::CompareImplicitConversionSequences(const ImplicitConversionSequence& ICS1,
1719 const ImplicitConversionSequence& ICS2)
1720{
1721 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
1722 // conversion sequences (as defined in 13.3.3.1)
1723 // -- a standard conversion sequence (13.3.3.1.1) is a better
1724 // conversion sequence than a user-defined conversion sequence or
1725 // an ellipsis conversion sequence, and
1726 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
1727 // conversion sequence than an ellipsis conversion sequence
1728 // (13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00001729 //
John McCall0d1da222010-01-12 00:44:57 +00001730 // C++0x [over.best.ics]p10:
1731 // For the purpose of ranking implicit conversion sequences as
1732 // described in 13.3.3.2, the ambiguous conversion sequence is
1733 // treated as a user-defined sequence that is indistinguishable
1734 // from any other user-defined conversion sequence.
1735 if (ICS1.getKind() < ICS2.getKind()) {
1736 if (!(ICS1.isUserDefined() && ICS2.isAmbiguous()))
1737 return ImplicitConversionSequence::Better;
1738 } else if (ICS2.getKind() < ICS1.getKind()) {
1739 if (!(ICS2.isUserDefined() && ICS1.isAmbiguous()))
1740 return ImplicitConversionSequence::Worse;
1741 }
1742
1743 if (ICS1.isAmbiguous() || ICS2.isAmbiguous())
1744 return ImplicitConversionSequence::Indistinguishable;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001745
1746 // Two implicit conversion sequences of the same form are
1747 // indistinguishable conversion sequences unless one of the
1748 // following rules apply: (C++ 13.3.3.2p3):
John McCall0d1da222010-01-12 00:44:57 +00001749 if (ICS1.isStandard())
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001750 return CompareStandardConversionSequences(ICS1.Standard, ICS2.Standard);
John McCall0d1da222010-01-12 00:44:57 +00001751 else if (ICS1.isUserDefined()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001752 // User-defined conversion sequence U1 is a better conversion
1753 // sequence than another user-defined conversion sequence U2 if
1754 // they contain the same user-defined conversion function or
1755 // constructor and if the second standard conversion sequence of
1756 // U1 is better than the second standard conversion sequence of
1757 // U2 (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00001758 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001759 ICS2.UserDefined.ConversionFunction)
1760 return CompareStandardConversionSequences(ICS1.UserDefined.After,
1761 ICS2.UserDefined.After);
1762 }
1763
1764 return ImplicitConversionSequence::Indistinguishable;
1765}
1766
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001767// Per 13.3.3.2p3, compare the given standard conversion sequences to
1768// determine if one is a proper subset of the other.
1769static ImplicitConversionSequence::CompareKind
1770compareStandardConversionSubsets(ASTContext &Context,
1771 const StandardConversionSequence& SCS1,
1772 const StandardConversionSequence& SCS2) {
1773 ImplicitConversionSequence::CompareKind Result
1774 = ImplicitConversionSequence::Indistinguishable;
1775
1776 if (SCS1.Second != SCS2.Second) {
1777 if (SCS1.Second == ICK_Identity)
1778 Result = ImplicitConversionSequence::Better;
1779 else if (SCS2.Second == ICK_Identity)
1780 Result = ImplicitConversionSequence::Worse;
1781 else
1782 return ImplicitConversionSequence::Indistinguishable;
1783 } else if (!Context.hasSameType(SCS1.getToType(1), SCS2.getToType(1)))
1784 return ImplicitConversionSequence::Indistinguishable;
1785
1786 if (SCS1.Third == SCS2.Third) {
1787 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
1788 : ImplicitConversionSequence::Indistinguishable;
1789 }
1790
1791 if (SCS1.Third == ICK_Identity)
1792 return Result == ImplicitConversionSequence::Worse
1793 ? ImplicitConversionSequence::Indistinguishable
1794 : ImplicitConversionSequence::Better;
1795
1796 if (SCS2.Third == ICK_Identity)
1797 return Result == ImplicitConversionSequence::Better
1798 ? ImplicitConversionSequence::Indistinguishable
1799 : ImplicitConversionSequence::Worse;
1800
1801 return ImplicitConversionSequence::Indistinguishable;
1802}
1803
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001804/// CompareStandardConversionSequences - Compare two standard
1805/// conversion sequences to determine whether one is better than the
1806/// other or if they are indistinguishable (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00001807ImplicitConversionSequence::CompareKind
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001808Sema::CompareStandardConversionSequences(const StandardConversionSequence& SCS1,
1809 const StandardConversionSequence& SCS2)
1810{
1811 // Standard conversion sequence S1 is a better conversion sequence
1812 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
1813
1814 // -- S1 is a proper subsequence of S2 (comparing the conversion
1815 // sequences in the canonical form defined by 13.3.3.1.1,
1816 // excluding any Lvalue Transformation; the identity conversion
1817 // sequence is considered to be a subsequence of any
1818 // non-identity conversion sequence) or, if not that,
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001819 if (ImplicitConversionSequence::CompareKind CK
1820 = compareStandardConversionSubsets(Context, SCS1, SCS2))
1821 return CK;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001822
1823 // -- the rank of S1 is better than the rank of S2 (by the rules
1824 // defined below), or, if not that,
1825 ImplicitConversionRank Rank1 = SCS1.getRank();
1826 ImplicitConversionRank Rank2 = SCS2.getRank();
1827 if (Rank1 < Rank2)
1828 return ImplicitConversionSequence::Better;
1829 else if (Rank2 < Rank1)
1830 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001831
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001832 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
1833 // are indistinguishable unless one of the following rules
1834 // applies:
Mike Stump11289f42009-09-09 15:08:12 +00001835
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001836 // A conversion that is not a conversion of a pointer, or
1837 // pointer to member, to bool is better than another conversion
1838 // that is such a conversion.
1839 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
1840 return SCS2.isPointerConversionToBool()
1841 ? ImplicitConversionSequence::Better
1842 : ImplicitConversionSequence::Worse;
1843
Douglas Gregor5c407d92008-10-23 00:40:37 +00001844 // C++ [over.ics.rank]p4b2:
1845 //
1846 // If class B is derived directly or indirectly from class A,
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001847 // conversion of B* to A* is better than conversion of B* to
1848 // void*, and conversion of A* to void* is better than conversion
1849 // of B* to void*.
Mike Stump11289f42009-09-09 15:08:12 +00001850 bool SCS1ConvertsToVoid
Douglas Gregor5c407d92008-10-23 00:40:37 +00001851 = SCS1.isPointerConversionToVoidPointer(Context);
Mike Stump11289f42009-09-09 15:08:12 +00001852 bool SCS2ConvertsToVoid
Douglas Gregor5c407d92008-10-23 00:40:37 +00001853 = SCS2.isPointerConversionToVoidPointer(Context);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001854 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
1855 // Exactly one of the conversion sequences is a conversion to
1856 // a void pointer; it's the worse conversion.
Douglas Gregor5c407d92008-10-23 00:40:37 +00001857 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
1858 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001859 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
1860 // Neither conversion sequence converts to a void pointer; compare
1861 // their derived-to-base conversions.
Douglas Gregor5c407d92008-10-23 00:40:37 +00001862 if (ImplicitConversionSequence::CompareKind DerivedCK
1863 = CompareDerivedToBaseConversions(SCS1, SCS2))
1864 return DerivedCK;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001865 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) {
1866 // Both conversion sequences are conversions to void
1867 // pointers. Compare the source types to determine if there's an
1868 // inheritance relationship in their sources.
John McCall0d1da222010-01-12 00:44:57 +00001869 QualType FromType1 = SCS1.getFromType();
1870 QualType FromType2 = SCS2.getFromType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001871
1872 // Adjust the types we're converting from via the array-to-pointer
1873 // conversion, if we need to.
1874 if (SCS1.First == ICK_Array_To_Pointer)
1875 FromType1 = Context.getArrayDecayedType(FromType1);
1876 if (SCS2.First == ICK_Array_To_Pointer)
1877 FromType2 = Context.getArrayDecayedType(FromType2);
1878
Douglas Gregor1aa450a2009-12-13 21:37:05 +00001879 QualType FromPointee1
1880 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
1881 QualType FromPointee2
1882 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001883
Douglas Gregor1aa450a2009-12-13 21:37:05 +00001884 if (IsDerivedFrom(FromPointee2, FromPointee1))
1885 return ImplicitConversionSequence::Better;
1886 else if (IsDerivedFrom(FromPointee1, FromPointee2))
1887 return ImplicitConversionSequence::Worse;
1888
1889 // Objective-C++: If one interface is more specific than the
1890 // other, it is the better one.
1891 const ObjCInterfaceType* FromIface1 = FromPointee1->getAs<ObjCInterfaceType>();
1892 const ObjCInterfaceType* FromIface2 = FromPointee2->getAs<ObjCInterfaceType>();
1893 if (FromIface1 && FromIface1) {
1894 if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1895 return ImplicitConversionSequence::Better;
1896 else if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1897 return ImplicitConversionSequence::Worse;
1898 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001899 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001900
1901 // Compare based on qualification conversions (C++ 13.3.3.2p3,
1902 // bullet 3).
Mike Stump11289f42009-09-09 15:08:12 +00001903 if (ImplicitConversionSequence::CompareKind QualCK
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001904 = CompareQualificationConversions(SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00001905 return QualCK;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001906
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001907 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Sebastian Redlb28b4072009-03-22 23:49:27 +00001908 // C++0x [over.ics.rank]p3b4:
1909 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
1910 // implicit object parameter of a non-static member function declared
1911 // without a ref-qualifier, and S1 binds an rvalue reference to an
1912 // rvalue and S2 binds an lvalue reference.
Sebastian Redl4c0cd852009-03-29 15:27:50 +00001913 // FIXME: We don't know if we're dealing with the implicit object parameter,
1914 // or if the member function in this case has a ref qualifier.
1915 // (Of course, we don't have ref qualifiers yet.)
1916 if (SCS1.RRefBinding != SCS2.RRefBinding)
1917 return SCS1.RRefBinding ? ImplicitConversionSequence::Better
1918 : ImplicitConversionSequence::Worse;
Sebastian Redlb28b4072009-03-22 23:49:27 +00001919
1920 // C++ [over.ics.rank]p3b4:
1921 // -- S1 and S2 are reference bindings (8.5.3), and the types to
1922 // which the references refer are the same type except for
1923 // top-level cv-qualifiers, and the type to which the reference
1924 // initialized by S2 refers is more cv-qualified than the type
1925 // to which the reference initialized by S1 refers.
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001926 QualType T1 = SCS1.getToType(2);
1927 QualType T2 = SCS2.getToType(2);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001928 T1 = Context.getCanonicalType(T1);
1929 T2 = Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00001930 Qualifiers T1Quals, T2Quals;
1931 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
1932 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
1933 if (UnqualT1 == UnqualT2) {
1934 // If the type is an array type, promote the element qualifiers to the type
1935 // for comparison.
1936 if (isa<ArrayType>(T1) && T1Quals)
1937 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
1938 if (isa<ArrayType>(T2) && T2Quals)
1939 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001940 if (T2.isMoreQualifiedThan(T1))
1941 return ImplicitConversionSequence::Better;
1942 else if (T1.isMoreQualifiedThan(T2))
1943 return ImplicitConversionSequence::Worse;
1944 }
1945 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001946
1947 return ImplicitConversionSequence::Indistinguishable;
1948}
1949
1950/// CompareQualificationConversions - Compares two standard conversion
1951/// sequences to determine whether they can be ranked based on their
Mike Stump11289f42009-09-09 15:08:12 +00001952/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
1953ImplicitConversionSequence::CompareKind
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001954Sema::CompareQualificationConversions(const StandardConversionSequence& SCS1,
Mike Stump11289f42009-09-09 15:08:12 +00001955 const StandardConversionSequence& SCS2) {
Douglas Gregor4b62ec62008-10-22 15:04:37 +00001956 // C++ 13.3.3.2p3:
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001957 // -- S1 and S2 differ only in their qualification conversion and
1958 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
1959 // cv-qualification signature of type T1 is a proper subset of
1960 // the cv-qualification signature of type T2, and S1 is not the
1961 // deprecated string literal array-to-pointer conversion (4.2).
1962 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
1963 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
1964 return ImplicitConversionSequence::Indistinguishable;
1965
1966 // FIXME: the example in the standard doesn't use a qualification
1967 // conversion (!)
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001968 QualType T1 = SCS1.getToType(2);
1969 QualType T2 = SCS2.getToType(2);
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001970 T1 = Context.getCanonicalType(T1);
1971 T2 = Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00001972 Qualifiers T1Quals, T2Quals;
1973 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
1974 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001975
1976 // If the types are the same, we won't learn anything by unwrapped
1977 // them.
Chandler Carruth607f38e2009-12-29 07:16:59 +00001978 if (UnqualT1 == UnqualT2)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001979 return ImplicitConversionSequence::Indistinguishable;
1980
Chandler Carruth607f38e2009-12-29 07:16:59 +00001981 // If the type is an array type, promote the element qualifiers to the type
1982 // for comparison.
1983 if (isa<ArrayType>(T1) && T1Quals)
1984 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
1985 if (isa<ArrayType>(T2) && T2Quals)
1986 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
1987
Mike Stump11289f42009-09-09 15:08:12 +00001988 ImplicitConversionSequence::CompareKind Result
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001989 = ImplicitConversionSequence::Indistinguishable;
1990 while (UnwrapSimilarPointerTypes(T1, T2)) {
1991 // Within each iteration of the loop, we check the qualifiers to
1992 // determine if this still looks like a qualification
1993 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00001994 // pointers or pointers-to-members and do it all again
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001995 // until there are no more pointers or pointers-to-members left
1996 // to unwrap. This essentially mimics what
1997 // IsQualificationConversion does, but here we're checking for a
1998 // strict subset of qualifiers.
1999 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
2000 // The qualifiers are the same, so this doesn't tell us anything
2001 // about how the sequences rank.
2002 ;
2003 else if (T2.isMoreQualifiedThan(T1)) {
2004 // T1 has fewer qualifiers, so it could be the better sequence.
2005 if (Result == ImplicitConversionSequence::Worse)
2006 // Neither has qualifiers that are a subset of the other's
2007 // qualifiers.
2008 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00002009
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002010 Result = ImplicitConversionSequence::Better;
2011 } else if (T1.isMoreQualifiedThan(T2)) {
2012 // T2 has fewer qualifiers, so it could be the better sequence.
2013 if (Result == ImplicitConversionSequence::Better)
2014 // Neither has qualifiers that are a subset of the other's
2015 // qualifiers.
2016 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00002017
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002018 Result = ImplicitConversionSequence::Worse;
2019 } else {
2020 // Qualifiers are disjoint.
2021 return ImplicitConversionSequence::Indistinguishable;
2022 }
2023
2024 // If the types after this point are equivalent, we're done.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002025 if (Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002026 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002027 }
2028
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002029 // Check that the winning standard conversion sequence isn't using
2030 // the deprecated string literal array to pointer conversion.
2031 switch (Result) {
2032 case ImplicitConversionSequence::Better:
Douglas Gregore489a7d2010-02-28 18:30:25 +00002033 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002034 Result = ImplicitConversionSequence::Indistinguishable;
2035 break;
2036
2037 case ImplicitConversionSequence::Indistinguishable:
2038 break;
2039
2040 case ImplicitConversionSequence::Worse:
Douglas Gregore489a7d2010-02-28 18:30:25 +00002041 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002042 Result = ImplicitConversionSequence::Indistinguishable;
2043 break;
2044 }
2045
2046 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002047}
2048
Douglas Gregor5c407d92008-10-23 00:40:37 +00002049/// CompareDerivedToBaseConversions - Compares two standard conversion
2050/// sequences to determine whether they can be ranked based on their
Douglas Gregor237f96c2008-11-26 23:31:11 +00002051/// various kinds of derived-to-base conversions (C++
2052/// [over.ics.rank]p4b3). As part of these checks, we also look at
2053/// conversions between Objective-C interface types.
Douglas Gregor5c407d92008-10-23 00:40:37 +00002054ImplicitConversionSequence::CompareKind
2055Sema::CompareDerivedToBaseConversions(const StandardConversionSequence& SCS1,
2056 const StandardConversionSequence& SCS2) {
John McCall0d1da222010-01-12 00:44:57 +00002057 QualType FromType1 = SCS1.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002058 QualType ToType1 = SCS1.getToType(1);
John McCall0d1da222010-01-12 00:44:57 +00002059 QualType FromType2 = SCS2.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002060 QualType ToType2 = SCS2.getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00002061
2062 // Adjust the types we're converting from via the array-to-pointer
2063 // conversion, if we need to.
2064 if (SCS1.First == ICK_Array_To_Pointer)
2065 FromType1 = Context.getArrayDecayedType(FromType1);
2066 if (SCS2.First == ICK_Array_To_Pointer)
2067 FromType2 = Context.getArrayDecayedType(FromType2);
2068
2069 // Canonicalize all of the types.
2070 FromType1 = Context.getCanonicalType(FromType1);
2071 ToType1 = Context.getCanonicalType(ToType1);
2072 FromType2 = Context.getCanonicalType(FromType2);
2073 ToType2 = Context.getCanonicalType(ToType2);
2074
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002075 // C++ [over.ics.rank]p4b3:
Douglas Gregor5c407d92008-10-23 00:40:37 +00002076 //
2077 // If class B is derived directly or indirectly from class A and
2078 // class C is derived directly or indirectly from B,
Douglas Gregor237f96c2008-11-26 23:31:11 +00002079 //
2080 // For Objective-C, we let A, B, and C also be Objective-C
2081 // interfaces.
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002082
2083 // Compare based on pointer conversions.
Mike Stump11289f42009-09-09 15:08:12 +00002084 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregora29dc052008-11-27 01:19:21 +00002085 SCS2.Second == ICK_Pointer_Conversion &&
2086 /*FIXME: Remove if Objective-C id conversions get their own rank*/
2087 FromType1->isPointerType() && FromType2->isPointerType() &&
2088 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00002089 QualType FromPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002090 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +00002091 QualType ToPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002092 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00002093 QualType FromPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002094 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00002095 QualType ToPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002096 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002097
John McCall9dd450b2009-09-21 23:43:11 +00002098 const ObjCInterfaceType* FromIface1 = FromPointee1->getAs<ObjCInterfaceType>();
2099 const ObjCInterfaceType* FromIface2 = FromPointee2->getAs<ObjCInterfaceType>();
2100 const ObjCInterfaceType* ToIface1 = ToPointee1->getAs<ObjCInterfaceType>();
2101 const ObjCInterfaceType* ToIface2 = ToPointee2->getAs<ObjCInterfaceType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002102
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002103 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregor5c407d92008-10-23 00:40:37 +00002104 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
2105 if (IsDerivedFrom(ToPointee1, ToPointee2))
2106 return ImplicitConversionSequence::Better;
2107 else if (IsDerivedFrom(ToPointee2, ToPointee1))
2108 return ImplicitConversionSequence::Worse;
Douglas Gregor237f96c2008-11-26 23:31:11 +00002109
2110 if (ToIface1 && ToIface2) {
2111 if (Context.canAssignObjCInterfaces(ToIface2, ToIface1))
2112 return ImplicitConversionSequence::Better;
2113 else if (Context.canAssignObjCInterfaces(ToIface1, ToIface2))
2114 return ImplicitConversionSequence::Worse;
2115 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00002116 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002117
2118 // -- conversion of B* to A* is better than conversion of C* to A*,
2119 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
2120 if (IsDerivedFrom(FromPointee2, FromPointee1))
2121 return ImplicitConversionSequence::Better;
2122 else if (IsDerivedFrom(FromPointee1, FromPointee2))
2123 return ImplicitConversionSequence::Worse;
Mike Stump11289f42009-09-09 15:08:12 +00002124
Douglas Gregor237f96c2008-11-26 23:31:11 +00002125 if (FromIface1 && FromIface2) {
2126 if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
2127 return ImplicitConversionSequence::Better;
2128 else if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
2129 return ImplicitConversionSequence::Worse;
2130 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002131 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00002132 }
2133
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00002134 // Ranking of member-pointer types.
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002135 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
2136 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
2137 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
2138 const MemberPointerType * FromMemPointer1 =
2139 FromType1->getAs<MemberPointerType>();
2140 const MemberPointerType * ToMemPointer1 =
2141 ToType1->getAs<MemberPointerType>();
2142 const MemberPointerType * FromMemPointer2 =
2143 FromType2->getAs<MemberPointerType>();
2144 const MemberPointerType * ToMemPointer2 =
2145 ToType2->getAs<MemberPointerType>();
2146 const Type *FromPointeeType1 = FromMemPointer1->getClass();
2147 const Type *ToPointeeType1 = ToMemPointer1->getClass();
2148 const Type *FromPointeeType2 = FromMemPointer2->getClass();
2149 const Type *ToPointeeType2 = ToMemPointer2->getClass();
2150 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
2151 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
2152 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
2153 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00002154 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002155 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
2156 if (IsDerivedFrom(ToPointee1, ToPointee2))
2157 return ImplicitConversionSequence::Worse;
2158 else if (IsDerivedFrom(ToPointee2, ToPointee1))
2159 return ImplicitConversionSequence::Better;
2160 }
2161 // conversion of B::* to C::* is better than conversion of A::* to C::*
2162 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
2163 if (IsDerivedFrom(FromPointee1, FromPointee2))
2164 return ImplicitConversionSequence::Better;
2165 else if (IsDerivedFrom(FromPointee2, FromPointee1))
2166 return ImplicitConversionSequence::Worse;
2167 }
2168 }
2169
Douglas Gregor83af86a2010-02-25 19:01:05 +00002170 if ((SCS1.ReferenceBinding || SCS1.CopyConstructor) &&
2171 (SCS2.ReferenceBinding || SCS2.CopyConstructor) &&
Douglas Gregor2fe98832008-11-03 19:09:14 +00002172 SCS1.Second == ICK_Derived_To_Base) {
2173 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor83af86a2010-02-25 19:01:05 +00002174 // -- binding of an expression of type C to a reference of type
2175 // B& is better than binding an expression of type C to a
2176 // reference of type 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(ToType1, ToType2))
2180 return ImplicitConversionSequence::Better;
2181 else if (IsDerivedFrom(ToType2, ToType1))
2182 return ImplicitConversionSequence::Worse;
2183 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002184
Douglas Gregor2fe98832008-11-03 19:09:14 +00002185 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor83af86a2010-02-25 19:01:05 +00002186 // -- binding of an expression of type B to a reference of type
2187 // A& is better than binding an expression of type C to a
2188 // reference of type A&,
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002189 if (!Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2190 Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00002191 if (IsDerivedFrom(FromType2, FromType1))
2192 return ImplicitConversionSequence::Better;
2193 else if (IsDerivedFrom(FromType1, FromType2))
2194 return ImplicitConversionSequence::Worse;
2195 }
2196 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002197
Douglas Gregor5c407d92008-10-23 00:40:37 +00002198 return ImplicitConversionSequence::Indistinguishable;
2199}
2200
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002201/// CompareReferenceRelationship - Compare the two types T1 and T2 to
2202/// determine whether they are reference-related,
2203/// reference-compatible, reference-compatible with added
2204/// qualification, or incompatible, for use in C++ initialization by
2205/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
2206/// type, and the first type (T1) is the pointee type of the reference
2207/// type being initialized.
2208Sema::ReferenceCompareResult
2209Sema::CompareReferenceRelationship(SourceLocation Loc,
2210 QualType OrigT1, QualType OrigT2,
2211 bool& DerivedToBase) {
2212 assert(!OrigT1->isReferenceType() &&
2213 "T1 must be the pointee type of the reference type");
2214 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
2215
2216 QualType T1 = Context.getCanonicalType(OrigT1);
2217 QualType T2 = Context.getCanonicalType(OrigT2);
2218 Qualifiers T1Quals, T2Quals;
2219 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
2220 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
2221
2222 // C++ [dcl.init.ref]p4:
2223 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
2224 // reference-related to "cv2 T2" if T1 is the same type as T2, or
2225 // T1 is a base class of T2.
2226 if (UnqualT1 == UnqualT2)
2227 DerivedToBase = false;
2228 else if (!RequireCompleteType(Loc, OrigT1, PDiag()) &&
2229 !RequireCompleteType(Loc, OrigT2, PDiag()) &&
2230 IsDerivedFrom(UnqualT2, UnqualT1))
2231 DerivedToBase = true;
2232 else
2233 return Ref_Incompatible;
2234
2235 // At this point, we know that T1 and T2 are reference-related (at
2236 // least).
2237
2238 // If the type is an array type, promote the element qualifiers to the type
2239 // for comparison.
2240 if (isa<ArrayType>(T1) && T1Quals)
2241 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
2242 if (isa<ArrayType>(T2) && T2Quals)
2243 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
2244
2245 // C++ [dcl.init.ref]p4:
2246 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
2247 // reference-related to T2 and cv1 is the same cv-qualification
2248 // as, or greater cv-qualification than, cv2. For purposes of
2249 // overload resolution, cases for which cv1 is greater
2250 // cv-qualification than cv2 are identified as
2251 // reference-compatible with added qualification (see 13.3.3.2).
2252 if (T1Quals.getCVRQualifiers() == T2Quals.getCVRQualifiers())
2253 return Ref_Compatible;
2254 else if (T1.isMoreQualifiedThan(T2))
2255 return Ref_Compatible_With_Added_Qualification;
2256 else
2257 return Ref_Related;
2258}
2259
2260/// \brief Compute an implicit conversion sequence for reference
2261/// initialization.
2262static ImplicitConversionSequence
2263TryReferenceInit(Sema &S, Expr *&Init, QualType DeclType,
2264 SourceLocation DeclLoc,
2265 bool SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00002266 bool AllowExplicit) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002267 assert(DeclType->isReferenceType() && "Reference init needs a reference");
2268
2269 // Most paths end in a failed conversion.
2270 ImplicitConversionSequence ICS;
2271 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
2272
2273 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
2274 QualType T2 = Init->getType();
2275
2276 // If the initializer is the address of an overloaded function, try
2277 // to resolve the overloaded function. If all goes well, T2 is the
2278 // type of the resulting function.
2279 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
2280 DeclAccessPair Found;
2281 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
2282 false, Found))
2283 T2 = Fn->getType();
2284 }
2285
2286 // Compute some basic properties of the types and the initializer.
2287 bool isRValRef = DeclType->isRValueReferenceType();
2288 bool DerivedToBase = false;
Douglas Gregoradc7a702010-04-16 17:45:54 +00002289 Expr::isLvalueResult InitLvalue = Init->isLvalue(S.Context);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002290 Sema::ReferenceCompareResult RefRelationship
2291 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase);
2292
2293 // C++ [dcl.init.ref]p5:
2294 // A reference to type "cv1 T1" is initialized by an expression
2295 // of type "cv2 T2" as follows:
2296
2297 // -- If the initializer expression
2298
2299 // C++ [over.ics.ref]p3:
2300 // Except for an implicit object parameter, for which see 13.3.1,
2301 // a standard conversion sequence cannot be formed if it requires
2302 // binding an lvalue reference to non-const to an rvalue or
2303 // binding an rvalue reference to an lvalue.
2304 if (isRValRef && InitLvalue == Expr::LV_Valid)
2305 return ICS;
2306
2307 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
2308 // reference-compatible with "cv2 T2," or
2309 //
2310 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
2311 if (InitLvalue == Expr::LV_Valid &&
2312 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
2313 // C++ [over.ics.ref]p1:
2314 // When a parameter of reference type binds directly (8.5.3)
2315 // to an argument expression, the implicit conversion sequence
2316 // is the identity conversion, unless the argument expression
2317 // has a type that is a derived class of the parameter type,
2318 // in which case the implicit conversion sequence is a
2319 // derived-to-base Conversion (13.3.3.1).
2320 ICS.setStandard();
2321 ICS.Standard.First = ICK_Identity;
2322 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
2323 ICS.Standard.Third = ICK_Identity;
2324 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
2325 ICS.Standard.setToType(0, T2);
2326 ICS.Standard.setToType(1, T1);
2327 ICS.Standard.setToType(2, T1);
2328 ICS.Standard.ReferenceBinding = true;
2329 ICS.Standard.DirectBinding = true;
2330 ICS.Standard.RRefBinding = false;
2331 ICS.Standard.CopyConstructor = 0;
2332
2333 // Nothing more to do: the inaccessibility/ambiguity check for
2334 // derived-to-base conversions is suppressed when we're
2335 // computing the implicit conversion sequence (C++
2336 // [over.best.ics]p2).
2337 return ICS;
2338 }
2339
2340 // -- has a class type (i.e., T2 is a class type), where T1 is
2341 // not reference-related to T2, and can be implicitly
2342 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
2343 // is reference-compatible with "cv3 T3" 92) (this
2344 // conversion is selected by enumerating the applicable
2345 // conversion functions (13.3.1.6) and choosing the best
2346 // one through overload resolution (13.3)),
2347 if (!isRValRef && !SuppressUserConversions && T2->isRecordType() &&
2348 !S.RequireCompleteType(DeclLoc, T2, 0) &&
2349 RefRelationship == Sema::Ref_Incompatible) {
2350 CXXRecordDecl *T2RecordDecl
2351 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
2352
2353 OverloadCandidateSet CandidateSet(DeclLoc);
2354 const UnresolvedSetImpl *Conversions
2355 = T2RecordDecl->getVisibleConversionFunctions();
2356 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
2357 E = Conversions->end(); I != E; ++I) {
2358 NamedDecl *D = *I;
2359 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2360 if (isa<UsingShadowDecl>(D))
2361 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2362
2363 FunctionTemplateDecl *ConvTemplate
2364 = dyn_cast<FunctionTemplateDecl>(D);
2365 CXXConversionDecl *Conv;
2366 if (ConvTemplate)
2367 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
2368 else
2369 Conv = cast<CXXConversionDecl>(D);
2370
2371 // If the conversion function doesn't return a reference type,
2372 // it can't be considered for this conversion.
2373 if (Conv->getConversionType()->isLValueReferenceType() &&
2374 (AllowExplicit || !Conv->isExplicit())) {
2375 if (ConvTemplate)
2376 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
2377 Init, DeclType, CandidateSet);
2378 else
2379 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
2380 DeclType, CandidateSet);
2381 }
2382 }
2383
2384 OverloadCandidateSet::iterator Best;
2385 switch (S.BestViableFunction(CandidateSet, DeclLoc, Best)) {
2386 case OR_Success:
2387 // C++ [over.ics.ref]p1:
2388 //
2389 // [...] If the parameter binds directly to the result of
2390 // applying a conversion function to the argument
2391 // expression, the implicit conversion sequence is a
2392 // user-defined conversion sequence (13.3.3.1.2), with the
2393 // second standard conversion sequence either an identity
2394 // conversion or, if the conversion function returns an
2395 // entity of a type that is a derived class of the parameter
2396 // type, a derived-to-base Conversion.
2397 if (!Best->FinalConversion.DirectBinding)
2398 break;
2399
2400 ICS.setUserDefined();
2401 ICS.UserDefined.Before = Best->Conversions[0].Standard;
2402 ICS.UserDefined.After = Best->FinalConversion;
2403 ICS.UserDefined.ConversionFunction = Best->Function;
2404 ICS.UserDefined.EllipsisConversion = false;
2405 assert(ICS.UserDefined.After.ReferenceBinding &&
2406 ICS.UserDefined.After.DirectBinding &&
2407 "Expected a direct reference binding!");
2408 return ICS;
2409
2410 case OR_Ambiguous:
2411 ICS.setAmbiguous();
2412 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
2413 Cand != CandidateSet.end(); ++Cand)
2414 if (Cand->Viable)
2415 ICS.Ambiguous.addConversion(Cand->Function);
2416 return ICS;
2417
2418 case OR_No_Viable_Function:
2419 case OR_Deleted:
2420 // There was no suitable conversion, or we found a deleted
2421 // conversion; continue with other checks.
2422 break;
2423 }
2424 }
2425
2426 // -- Otherwise, the reference shall be to a non-volatile const
2427 // type (i.e., cv1 shall be const), or the reference shall be an
2428 // rvalue reference and the initializer expression shall be an rvalue.
2429 if (!isRValRef && T1.getCVRQualifiers() != Qualifiers::Const)
2430 return ICS;
2431
2432 // -- If the initializer expression is an rvalue, with T2 a
2433 // class type, and "cv1 T1" is reference-compatible with
2434 // "cv2 T2," the reference is bound in one of the
2435 // following ways (the choice is implementation-defined):
2436 //
2437 // -- The reference is bound to the object represented by
2438 // the rvalue (see 3.10) or to a sub-object within that
2439 // object.
2440 //
2441 // -- A temporary of type "cv1 T2" [sic] is created, and
2442 // a constructor is called to copy the entire rvalue
2443 // object into the temporary. The reference is bound to
2444 // the temporary or to a sub-object within the
2445 // temporary.
2446 //
2447 // The constructor that would be used to make the copy
2448 // shall be callable whether or not the copy is actually
2449 // done.
2450 //
2451 // Note that C++0x [dcl.init.ref]p5 takes away this implementation
2452 // freedom, so we will always take the first option and never build
2453 // a temporary in this case.
2454 if (InitLvalue != Expr::LV_Valid && T2->isRecordType() &&
2455 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
2456 ICS.setStandard();
2457 ICS.Standard.First = ICK_Identity;
2458 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
2459 ICS.Standard.Third = ICK_Identity;
2460 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
2461 ICS.Standard.setToType(0, T2);
2462 ICS.Standard.setToType(1, T1);
2463 ICS.Standard.setToType(2, T1);
2464 ICS.Standard.ReferenceBinding = true;
2465 ICS.Standard.DirectBinding = false;
2466 ICS.Standard.RRefBinding = isRValRef;
2467 ICS.Standard.CopyConstructor = 0;
2468 return ICS;
2469 }
2470
2471 // -- Otherwise, a temporary of type "cv1 T1" is created and
2472 // initialized from the initializer expression using the
2473 // rules for a non-reference copy initialization (8.5). The
2474 // reference is then bound to the temporary. If T1 is
2475 // reference-related to T2, cv1 must be the same
2476 // cv-qualification as, or greater cv-qualification than,
2477 // cv2; otherwise, the program is ill-formed.
2478 if (RefRelationship == Sema::Ref_Related) {
2479 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
2480 // we would be reference-compatible or reference-compatible with
2481 // added qualification. But that wasn't the case, so the reference
2482 // initialization fails.
2483 return ICS;
2484 }
2485
2486 // If at least one of the types is a class type, the types are not
2487 // related, and we aren't allowed any user conversions, the
2488 // reference binding fails. This case is important for breaking
2489 // recursion, since TryImplicitConversion below will attempt to
2490 // create a temporary through the use of a copy constructor.
2491 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
2492 (T1->isRecordType() || T2->isRecordType()))
2493 return ICS;
2494
2495 // C++ [over.ics.ref]p2:
2496 //
2497 // When a parameter of reference type is not bound directly to
2498 // an argument expression, the conversion sequence is the one
2499 // required to convert the argument expression to the
2500 // underlying type of the reference according to
2501 // 13.3.3.1. Conceptually, this conversion sequence corresponds
2502 // to copy-initializing a temporary of the underlying type with
2503 // the argument expression. Any difference in top-level
2504 // cv-qualification is subsumed by the initialization itself
2505 // and does not constitute a conversion.
2506 ICS = S.TryImplicitConversion(Init, T1, SuppressUserConversions,
2507 /*AllowExplicit=*/false,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002508 /*InOverloadResolution=*/false);
2509
2510 // Of course, that's still a reference binding.
2511 if (ICS.isStandard()) {
2512 ICS.Standard.ReferenceBinding = true;
2513 ICS.Standard.RRefBinding = isRValRef;
2514 } else if (ICS.isUserDefined()) {
2515 ICS.UserDefined.After.ReferenceBinding = true;
2516 ICS.UserDefined.After.RRefBinding = isRValRef;
2517 }
2518 return ICS;
2519}
2520
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002521/// TryCopyInitialization - Try to copy-initialize a value of type
2522/// ToType from the expression From. Return the implicit conversion
2523/// sequence required to pass this argument, which may be a bad
2524/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor2fe98832008-11-03 19:09:14 +00002525/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregore81335c2010-04-16 18:00:29 +00002526/// do not permit any user-defined conversion sequences.
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00002527static ImplicitConversionSequence
2528TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
Douglas Gregordcd27ff2010-04-16 17:53:55 +00002529 bool SuppressUserConversions,
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00002530 bool InOverloadResolution) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002531 if (ToType->isReferenceType())
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00002532 return TryReferenceInit(S, From, ToType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002533 /*FIXME:*/From->getLocStart(),
2534 SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00002535 /*AllowExplicit=*/false);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002536
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00002537 return S.TryImplicitConversion(From, ToType,
2538 SuppressUserConversions,
2539 /*AllowExplicit=*/false,
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00002540 InOverloadResolution);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002541}
2542
Douglas Gregor436424c2008-11-18 23:14:02 +00002543/// TryObjectArgumentInitialization - Try to initialize the object
2544/// parameter of the given member function (@c Method) from the
2545/// expression @p From.
2546ImplicitConversionSequence
John McCall47000992010-01-14 03:28:57 +00002547Sema::TryObjectArgumentInitialization(QualType OrigFromType,
John McCall6e9f8f62009-12-03 04:06:58 +00002548 CXXMethodDecl *Method,
2549 CXXRecordDecl *ActingContext) {
2550 QualType ClassType = Context.getTypeDeclType(ActingContext);
Sebastian Redl931e0bd2009-11-18 20:55:52 +00002551 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
2552 // const volatile object.
2553 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
2554 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
2555 QualType ImplicitParamType = Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor436424c2008-11-18 23:14:02 +00002556
2557 // Set up the conversion sequence as a "bad" conversion, to allow us
2558 // to exit early.
2559 ImplicitConversionSequence ICS;
Douglas Gregor436424c2008-11-18 23:14:02 +00002560
2561 // We need to have an object of class type.
John McCall47000992010-01-14 03:28:57 +00002562 QualType FromType = OrigFromType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002563 if (const PointerType *PT = FromType->getAs<PointerType>())
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002564 FromType = PT->getPointeeType();
2565
2566 assert(FromType->isRecordType());
Douglas Gregor436424c2008-11-18 23:14:02 +00002567
Sebastian Redl931e0bd2009-11-18 20:55:52 +00002568 // The implicit object parameter is has the type "reference to cv X",
Douglas Gregor436424c2008-11-18 23:14:02 +00002569 // where X is the class of which the function is a member
2570 // (C++ [over.match.funcs]p4). However, when finding an implicit
2571 // conversion sequence for the argument, we are not allowed to
Mike Stump11289f42009-09-09 15:08:12 +00002572 // create temporaries or perform user-defined conversions
Douglas Gregor436424c2008-11-18 23:14:02 +00002573 // (C++ [over.match.funcs]p5). We perform a simplified version of
2574 // reference binding here, that allows class rvalues to bind to
2575 // non-constant references.
2576
2577 // First check the qualifiers. We don't care about lvalue-vs-rvalue
2578 // with the implicit object parameter (C++ [over.match.funcs]p5).
2579 QualType FromTypeCanon = Context.getCanonicalType(FromType);
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002580 if (ImplicitParamType.getCVRQualifiers()
2581 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCall6a61b522010-01-13 09:16:55 +00002582 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCall65eb8792010-02-25 01:37:24 +00002583 ICS.setBad(BadConversionSequence::bad_qualifiers,
2584 OrigFromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00002585 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00002586 }
Douglas Gregor436424c2008-11-18 23:14:02 +00002587
2588 // Check that we have either the same type or a derived type. It
2589 // affects the conversion rank.
2590 QualType ClassTypeCanon = Context.getCanonicalType(ClassType);
John McCall65eb8792010-02-25 01:37:24 +00002591 ImplicitConversionKind SecondKind;
2592 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
2593 SecondKind = ICK_Identity;
2594 } else if (IsDerivedFrom(FromType, ClassType))
2595 SecondKind = ICK_Derived_To_Base;
John McCall6a61b522010-01-13 09:16:55 +00002596 else {
John McCall65eb8792010-02-25 01:37:24 +00002597 ICS.setBad(BadConversionSequence::unrelated_class,
2598 FromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00002599 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00002600 }
Douglas Gregor436424c2008-11-18 23:14:02 +00002601
2602 // Success. Mark this as a reference binding.
John McCall0d1da222010-01-12 00:44:57 +00002603 ICS.setStandard();
John McCall65eb8792010-02-25 01:37:24 +00002604 ICS.Standard.setAsIdentityConversion();
2605 ICS.Standard.Second = SecondKind;
John McCall0d1da222010-01-12 00:44:57 +00002606 ICS.Standard.setFromType(FromType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002607 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00002608 ICS.Standard.ReferenceBinding = true;
2609 ICS.Standard.DirectBinding = true;
Sebastian Redlf69a94a2009-03-29 22:46:24 +00002610 ICS.Standard.RRefBinding = false;
Douglas Gregor436424c2008-11-18 23:14:02 +00002611 return ICS;
2612}
2613
2614/// PerformObjectArgumentInitialization - Perform initialization of
2615/// the implicit object parameter for the given Method with the given
2616/// expression.
2617bool
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002618Sema::PerformObjectArgumentInitialization(Expr *&From,
2619 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00002620 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002621 CXXMethodDecl *Method) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002622 QualType FromRecordType, DestType;
Mike Stump11289f42009-09-09 15:08:12 +00002623 QualType ImplicitParamRecordType =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002624 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00002625
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002626 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002627 FromRecordType = PT->getPointeeType();
2628 DestType = Method->getThisType(Context);
2629 } else {
2630 FromRecordType = From->getType();
2631 DestType = ImplicitParamRecordType;
2632 }
2633
John McCall6e9f8f62009-12-03 04:06:58 +00002634 // Note that we always use the true parent context when performing
2635 // the actual argument initialization.
Mike Stump11289f42009-09-09 15:08:12 +00002636 ImplicitConversionSequence ICS
John McCall6e9f8f62009-12-03 04:06:58 +00002637 = TryObjectArgumentInitialization(From->getType(), Method,
2638 Method->getParent());
John McCall0d1da222010-01-12 00:44:57 +00002639 if (ICS.isBad())
Douglas Gregor436424c2008-11-18 23:14:02 +00002640 return Diag(From->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00002641 diag::err_implicit_object_parameter_init)
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002642 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002643
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002644 if (ICS.Standard.Second == ICK_Derived_To_Base)
John McCall16df1e52010-03-30 21:47:33 +00002645 return PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
Douglas Gregor436424c2008-11-18 23:14:02 +00002646
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002647 if (!Context.hasSameType(From->getType(), DestType))
2648 ImpCastExprToType(From, DestType, CastExpr::CK_NoOp,
2649 /*isLvalue=*/!From->getType()->getAs<PointerType>());
Douglas Gregor436424c2008-11-18 23:14:02 +00002650 return false;
2651}
2652
Douglas Gregor5fb53972009-01-14 15:45:31 +00002653/// TryContextuallyConvertToBool - Attempt to contextually convert the
2654/// expression From to bool (C++0x [conv]p3).
2655ImplicitConversionSequence Sema::TryContextuallyConvertToBool(Expr *From) {
Mike Stump11289f42009-09-09 15:08:12 +00002656 return TryImplicitConversion(From, Context.BoolTy,
Anders Carlssonef4c7212009-08-27 17:24:15 +00002657 // FIXME: Are these flags correct?
2658 /*SuppressUserConversions=*/false,
Mike Stump11289f42009-09-09 15:08:12 +00002659 /*AllowExplicit=*/true,
Anders Carlsson228eea32009-08-28 15:33:32 +00002660 /*InOverloadResolution=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00002661}
2662
2663/// PerformContextuallyConvertToBool - Perform a contextual conversion
2664/// of the expression From to bool (C++0x [conv]p3).
2665bool Sema::PerformContextuallyConvertToBool(Expr *&From) {
2666 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(From);
John McCall0d1da222010-01-12 00:44:57 +00002667 if (!ICS.isBad())
2668 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002669
Fariborz Jahanian76197412009-11-18 18:26:29 +00002670 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002671 return Diag(From->getSourceRange().getBegin(),
2672 diag::err_typecheck_bool_condition)
2673 << From->getType() << From->getSourceRange();
2674 return true;
Douglas Gregor5fb53972009-01-14 15:45:31 +00002675}
2676
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002677/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor2fe98832008-11-03 19:09:14 +00002678/// candidate functions, using the given function call arguments. If
2679/// @p SuppressUserConversions, then don't allow user-defined
2680/// conversions via constructors or conversion operators.
Douglas Gregorcabea402009-09-22 15:41:20 +00002681///
2682/// \para PartialOverloading true if we are performing "partial" overloading
2683/// based on an incomplete set of function arguments. This feature is used by
2684/// code completion.
Mike Stump11289f42009-09-09 15:08:12 +00002685void
2686Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCalla0296f72010-03-19 07:35:19 +00002687 DeclAccessPair FoundDecl,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002688 Expr **Args, unsigned NumArgs,
Douglas Gregor2fe98832008-11-03 19:09:14 +00002689 OverloadCandidateSet& CandidateSet,
Sebastian Redl42e92c42009-04-12 17:16:29 +00002690 bool SuppressUserConversions,
Douglas Gregorcabea402009-09-22 15:41:20 +00002691 bool PartialOverloading) {
Mike Stump11289f42009-09-09 15:08:12 +00002692 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00002693 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002694 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump11289f42009-09-09 15:08:12 +00002695 assert(!Function->getDescribedFunctionTemplate() &&
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002696 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump11289f42009-09-09 15:08:12 +00002697
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002698 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00002699 if (!isa<CXXConstructorDecl>(Method)) {
2700 // If we get here, it's because we're calling a member function
2701 // that is named without a member access expression (e.g.,
2702 // "this->f") that was either written explicitly or created
2703 // implicitly. This can happen with a qualified call to a member
John McCall6e9f8f62009-12-03 04:06:58 +00002704 // function, e.g., X::f(). We use an empty type for the implied
2705 // object argument (C++ [over.call.func]p3), and the acting context
2706 // is irrelevant.
John McCalla0296f72010-03-19 07:35:19 +00002707 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
John McCall6e9f8f62009-12-03 04:06:58 +00002708 QualType(), Args, NumArgs, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00002709 SuppressUserConversions);
Sebastian Redl1a99f442009-04-16 17:51:27 +00002710 return;
2711 }
2712 // We treat a constructor like a non-member function, since its object
2713 // argument doesn't participate in overload resolution.
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002714 }
2715
Douglas Gregorff7028a2009-11-13 23:59:09 +00002716 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002717 return;
Douglas Gregorffe14e32009-11-14 01:20:54 +00002718
Douglas Gregor27381f32009-11-23 12:27:39 +00002719 // Overload resolution is always an unevaluated context.
2720 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
2721
Douglas Gregorffe14e32009-11-14 01:20:54 +00002722 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
2723 // C++ [class.copy]p3:
2724 // A member function template is never instantiated to perform the copy
2725 // of a class object to an object of its class type.
2726 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
2727 if (NumArgs == 1 &&
2728 Constructor->isCopyConstructorLikeSpecialization() &&
Douglas Gregor901e7172010-02-21 18:30:38 +00002729 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
2730 IsDerivedFrom(Args[0]->getType(), ClassType)))
Douglas Gregorffe14e32009-11-14 01:20:54 +00002731 return;
2732 }
2733
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002734 // Add this candidate
2735 CandidateSet.push_back(OverloadCandidate());
2736 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00002737 Candidate.FoundDecl = FoundDecl;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002738 Candidate.Function = Function;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002739 Candidate.Viable = true;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002740 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002741 Candidate.IgnoreObjectArgument = false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002742
2743 unsigned NumArgsInProto = Proto->getNumArgs();
2744
2745 // (C++ 13.3.2p2): A candidate function having fewer than m
2746 // parameters is viable only if it has an ellipsis in its parameter
2747 // list (8.3.5).
Douglas Gregor2a920012009-09-23 14:56:09 +00002748 if ((NumArgs + (PartialOverloading && NumArgs)) > NumArgsInProto &&
2749 !Proto->isVariadic()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002750 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002751 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002752 return;
2753 }
2754
2755 // (C++ 13.3.2p2): A candidate function having more than m parameters
2756 // is viable only if the (m+1)st parameter has a default argument
2757 // (8.3.6). For the purposes of overload resolution, the
2758 // parameter list is truncated on the right, so that there are
2759 // exactly m parameters.
2760 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Douglas Gregorcabea402009-09-22 15:41:20 +00002761 if (NumArgs < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002762 // Not enough arguments.
2763 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002764 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002765 return;
2766 }
2767
2768 // Determine the implicit conversion sequences for each of the
2769 // arguments.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002770 Candidate.Conversions.resize(NumArgs);
2771 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2772 if (ArgIdx < NumArgsInProto) {
2773 // (C++ 13.3.2p3): for F to be a viable function, there shall
2774 // exist for each argument an implicit conversion sequence
2775 // (13.3.3.1) that converts that argument to the corresponding
2776 // parameter of F.
2777 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00002778 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00002779 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Douglas Gregorb05275a2010-04-16 17:41:49 +00002780 SuppressUserConversions,
Anders Carlsson20d13322009-08-27 17:37:39 +00002781 /*InOverloadResolution=*/true);
John McCall0d1da222010-01-12 00:44:57 +00002782 if (Candidate.Conversions[ArgIdx].isBad()) {
2783 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002784 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall0d1da222010-01-12 00:44:57 +00002785 break;
Douglas Gregor436424c2008-11-18 23:14:02 +00002786 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002787 } else {
2788 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2789 // argument for which there is no corresponding parameter is
2790 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00002791 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002792 }
2793 }
2794}
2795
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002796/// \brief Add all of the function declarations in the given function set to
2797/// the overload canddiate set.
John McCall4c4c1df2010-01-26 03:27:55 +00002798void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002799 Expr **Args, unsigned NumArgs,
2800 OverloadCandidateSet& CandidateSet,
2801 bool SuppressUserConversions) {
John McCall4c4c1df2010-01-26 03:27:55 +00002802 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCalla0296f72010-03-19 07:35:19 +00002803 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
2804 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002805 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00002806 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00002807 cast<CXXMethodDecl>(FD)->getParent(),
2808 Args[0]->getType(), Args + 1, NumArgs - 1,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002809 CandidateSet, SuppressUserConversions);
2810 else
John McCalla0296f72010-03-19 07:35:19 +00002811 AddOverloadCandidate(FD, F.getPair(), Args, NumArgs, CandidateSet,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002812 SuppressUserConversions);
2813 } else {
John McCalla0296f72010-03-19 07:35:19 +00002814 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002815 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
2816 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00002817 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00002818 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
John McCall6b51f282009-11-23 01:53:49 +00002819 /*FIXME: explicit args */ 0,
John McCall6e9f8f62009-12-03 04:06:58 +00002820 Args[0]->getType(), Args + 1, NumArgs - 1,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002821 CandidateSet,
Douglas Gregor15448f82009-06-27 21:05:07 +00002822 SuppressUserConversions);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002823 else
John McCalla0296f72010-03-19 07:35:19 +00002824 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
John McCall6b51f282009-11-23 01:53:49 +00002825 /*FIXME: explicit args */ 0,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002826 Args, NumArgs, CandidateSet,
2827 SuppressUserConversions);
2828 }
Douglas Gregor15448f82009-06-27 21:05:07 +00002829 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002830}
2831
John McCallf0f1cf02009-11-17 07:50:12 +00002832/// AddMethodCandidate - Adds a named decl (which is some kind of
2833/// method) as a method candidate to the given overload set.
John McCalla0296f72010-03-19 07:35:19 +00002834void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00002835 QualType ObjectType,
John McCallf0f1cf02009-11-17 07:50:12 +00002836 Expr **Args, unsigned NumArgs,
2837 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00002838 bool SuppressUserConversions) {
John McCalla0296f72010-03-19 07:35:19 +00002839 NamedDecl *Decl = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00002840 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCallf0f1cf02009-11-17 07:50:12 +00002841
2842 if (isa<UsingShadowDecl>(Decl))
2843 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
2844
2845 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
2846 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
2847 "Expected a member function template");
John McCalla0296f72010-03-19 07:35:19 +00002848 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
2849 /*ExplicitArgs*/ 0,
John McCall6e9f8f62009-12-03 04:06:58 +00002850 ObjectType, Args, NumArgs,
John McCallf0f1cf02009-11-17 07:50:12 +00002851 CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00002852 SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00002853 } else {
John McCalla0296f72010-03-19 07:35:19 +00002854 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
John McCall6e9f8f62009-12-03 04:06:58 +00002855 ObjectType, Args, NumArgs,
Douglas Gregorf1e46692010-04-16 17:33:27 +00002856 CandidateSet, SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00002857 }
2858}
2859
Douglas Gregor436424c2008-11-18 23:14:02 +00002860/// AddMethodCandidate - Adds the given C++ member function to the set
2861/// of candidate functions, using the given function call arguments
2862/// and the object argument (@c Object). For example, in a call
2863/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
2864/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
2865/// allow user-defined conversions via constructors or conversion
Douglas Gregorf1e46692010-04-16 17:33:27 +00002866/// operators.
Mike Stump11289f42009-09-09 15:08:12 +00002867void
John McCalla0296f72010-03-19 07:35:19 +00002868Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00002869 CXXRecordDecl *ActingContext, QualType ObjectType,
2870 Expr **Args, unsigned NumArgs,
Douglas Gregor436424c2008-11-18 23:14:02 +00002871 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00002872 bool SuppressUserConversions) {
Mike Stump11289f42009-09-09 15:08:12 +00002873 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00002874 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor436424c2008-11-18 23:14:02 +00002875 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl1a99f442009-04-16 17:51:27 +00002876 assert(!isa<CXXConstructorDecl>(Method) &&
2877 "Use AddOverloadCandidate for constructors");
Douglas Gregor436424c2008-11-18 23:14:02 +00002878
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002879 if (!CandidateSet.isNewCandidate(Method))
2880 return;
2881
Douglas Gregor27381f32009-11-23 12:27:39 +00002882 // Overload resolution is always an unevaluated context.
2883 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
2884
Douglas Gregor436424c2008-11-18 23:14:02 +00002885 // Add this candidate
2886 CandidateSet.push_back(OverloadCandidate());
2887 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00002888 Candidate.FoundDecl = FoundDecl;
Douglas Gregor436424c2008-11-18 23:14:02 +00002889 Candidate.Function = Method;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002890 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002891 Candidate.IgnoreObjectArgument = false;
Douglas Gregor436424c2008-11-18 23:14:02 +00002892
2893 unsigned NumArgsInProto = Proto->getNumArgs();
2894
2895 // (C++ 13.3.2p2): A candidate function having fewer than m
2896 // parameters is viable only if it has an ellipsis in its parameter
2897 // list (8.3.5).
2898 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2899 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002900 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00002901 return;
2902 }
2903
2904 // (C++ 13.3.2p2): A candidate function having more than m parameters
2905 // is viable only if the (m+1)st parameter has a default argument
2906 // (8.3.6). For the purposes of overload resolution, the
2907 // parameter list is truncated on the right, so that there are
2908 // exactly m parameters.
2909 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
2910 if (NumArgs < MinRequiredArgs) {
2911 // Not enough arguments.
2912 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002913 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00002914 return;
2915 }
2916
2917 Candidate.Viable = true;
2918 Candidate.Conversions.resize(NumArgs + 1);
2919
John McCall6e9f8f62009-12-03 04:06:58 +00002920 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002921 // The implicit object argument is ignored.
2922 Candidate.IgnoreObjectArgument = true;
2923 else {
2924 // Determine the implicit conversion sequence for the object
2925 // parameter.
John McCall6e9f8f62009-12-03 04:06:58 +00002926 Candidate.Conversions[0]
2927 = TryObjectArgumentInitialization(ObjectType, Method, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00002928 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002929 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002930 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002931 return;
2932 }
Douglas Gregor436424c2008-11-18 23:14:02 +00002933 }
2934
2935 // Determine the implicit conversion sequences for each of the
2936 // arguments.
2937 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2938 if (ArgIdx < NumArgsInProto) {
2939 // (C++ 13.3.2p3): for F to be a viable function, there shall
2940 // exist for each argument an implicit conversion sequence
2941 // (13.3.3.1) that converts that argument to the corresponding
2942 // parameter of F.
2943 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00002944 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00002945 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Douglas Gregorf1e46692010-04-16 17:33:27 +00002946 SuppressUserConversions,
Anders Carlsson228eea32009-08-28 15:33:32 +00002947 /*InOverloadResolution=*/true);
John McCall0d1da222010-01-12 00:44:57 +00002948 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00002949 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002950 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00002951 break;
2952 }
2953 } else {
2954 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2955 // argument for which there is no corresponding parameter is
2956 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00002957 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor436424c2008-11-18 23:14:02 +00002958 }
2959 }
2960}
2961
Douglas Gregor97628d62009-08-21 00:16:32 +00002962/// \brief Add a C++ member function template as a candidate to the candidate
2963/// set, using template argument deduction to produce an appropriate member
2964/// function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00002965void
Douglas Gregor97628d62009-08-21 00:16:32 +00002966Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCalla0296f72010-03-19 07:35:19 +00002967 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00002968 CXXRecordDecl *ActingContext,
John McCall6b51f282009-11-23 01:53:49 +00002969 const TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00002970 QualType ObjectType,
2971 Expr **Args, unsigned NumArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00002972 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00002973 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002974 if (!CandidateSet.isNewCandidate(MethodTmpl))
2975 return;
2976
Douglas Gregor97628d62009-08-21 00:16:32 +00002977 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00002978 // In each case where a candidate is a function template, candidate
Douglas Gregor97628d62009-08-21 00:16:32 +00002979 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00002980 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor97628d62009-08-21 00:16:32 +00002981 // candidate functions in the usual way.113) A given name can refer to one
2982 // or more function templates and also to a set of overloaded non-template
2983 // functions. In such a case, the candidate functions generated from each
2984 // function template are combined with the set of non-template candidate
2985 // functions.
John McCallbc077cf2010-02-08 23:07:23 +00002986 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor97628d62009-08-21 00:16:32 +00002987 FunctionDecl *Specialization = 0;
2988 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00002989 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00002990 Args, NumArgs, Specialization, Info)) {
2991 // FIXME: Record what happened with template argument deduction, so
2992 // that we can give the user a beautiful diagnostic.
2993 (void)Result;
2994 return;
2995 }
Mike Stump11289f42009-09-09 15:08:12 +00002996
Douglas Gregor97628d62009-08-21 00:16:32 +00002997 // Add the function template specialization produced by template argument
2998 // deduction as a candidate.
2999 assert(Specialization && "Missing member function template specialization?");
Mike Stump11289f42009-09-09 15:08:12 +00003000 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor97628d62009-08-21 00:16:32 +00003001 "Specialization is not a member function?");
John McCalla0296f72010-03-19 07:35:19 +00003002 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00003003 ActingContext, ObjectType, Args, NumArgs,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003004 CandidateSet, SuppressUserConversions);
Douglas Gregor97628d62009-08-21 00:16:32 +00003005}
3006
Douglas Gregor05155d82009-08-21 23:19:43 +00003007/// \brief Add a C++ function template specialization as a candidate
3008/// in the candidate set, using template argument deduction to produce
3009/// an appropriate function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00003010void
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003011Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00003012 DeclAccessPair FoundDecl,
John McCall6b51f282009-11-23 01:53:49 +00003013 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003014 Expr **Args, unsigned NumArgs,
3015 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003016 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003017 if (!CandidateSet.isNewCandidate(FunctionTemplate))
3018 return;
3019
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003020 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00003021 // In each case where a candidate is a function template, candidate
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003022 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00003023 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003024 // candidate functions in the usual way.113) A given name can refer to one
3025 // or more function templates and also to a set of overloaded non-template
3026 // functions. In such a case, the candidate functions generated from each
3027 // function template are combined with the set of non-template candidate
3028 // functions.
John McCallbc077cf2010-02-08 23:07:23 +00003029 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003030 FunctionDecl *Specialization = 0;
3031 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00003032 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00003033 Args, NumArgs, Specialization, Info)) {
John McCalld681c392009-12-16 08:11:27 +00003034 CandidateSet.push_back(OverloadCandidate());
3035 OverloadCandidate &Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003036 Candidate.FoundDecl = FoundDecl;
John McCalld681c392009-12-16 08:11:27 +00003037 Candidate.Function = FunctionTemplate->getTemplatedDecl();
3038 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003039 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCalld681c392009-12-16 08:11:27 +00003040 Candidate.IsSurrogate = false;
3041 Candidate.IgnoreObjectArgument = false;
John McCall8b9ed552010-02-01 18:53:26 +00003042
3043 // TODO: record more information about failed template arguments
3044 Candidate.DeductionFailure.Result = Result;
3045 Candidate.DeductionFailure.TemplateParameter = Info.Param.getOpaqueValue();
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003046 return;
3047 }
Mike Stump11289f42009-09-09 15:08:12 +00003048
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003049 // Add the function template specialization produced by template argument
3050 // deduction as a candidate.
3051 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00003052 AddOverloadCandidate(Specialization, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003053 SuppressUserConversions);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003054}
Mike Stump11289f42009-09-09 15:08:12 +00003055
Douglas Gregora1f013e2008-11-07 22:36:19 +00003056/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump11289f42009-09-09 15:08:12 +00003057/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregora1f013e2008-11-07 22:36:19 +00003058/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump11289f42009-09-09 15:08:12 +00003059/// and ToType is the type that we're eventually trying to convert to
Douglas Gregora1f013e2008-11-07 22:36:19 +00003060/// (which may or may not be the same type as the type that the
3061/// conversion function produces).
3062void
3063Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00003064 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00003065 CXXRecordDecl *ActingContext,
Douglas Gregora1f013e2008-11-07 22:36:19 +00003066 Expr *From, QualType ToType,
3067 OverloadCandidateSet& CandidateSet) {
Douglas Gregor05155d82009-08-21 23:19:43 +00003068 assert(!Conversion->getDescribedFunctionTemplate() &&
3069 "Conversion function templates use AddTemplateConversionCandidate");
3070
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003071 if (!CandidateSet.isNewCandidate(Conversion))
3072 return;
3073
Douglas Gregor27381f32009-11-23 12:27:39 +00003074 // Overload resolution is always an unevaluated context.
3075 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
3076
Douglas Gregora1f013e2008-11-07 22:36:19 +00003077 // Add this candidate
3078 CandidateSet.push_back(OverloadCandidate());
3079 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003080 Candidate.FoundDecl = FoundDecl;
Douglas Gregora1f013e2008-11-07 22:36:19 +00003081 Candidate.Function = Conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003082 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003083 Candidate.IgnoreObjectArgument = false;
Douglas Gregora1f013e2008-11-07 22:36:19 +00003084 Candidate.FinalConversion.setAsIdentityConversion();
John McCall0d1da222010-01-12 00:44:57 +00003085 Candidate.FinalConversion.setFromType(Conversion->getConversionType());
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003086 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregora1f013e2008-11-07 22:36:19 +00003087
Douglas Gregor436424c2008-11-18 23:14:02 +00003088 // Determine the implicit conversion sequence for the implicit
3089 // object parameter.
Douglas Gregora1f013e2008-11-07 22:36:19 +00003090 Candidate.Viable = true;
3091 Candidate.Conversions.resize(1);
John McCall6e9f8f62009-12-03 04:06:58 +00003092 Candidate.Conversions[0]
3093 = TryObjectArgumentInitialization(From->getType(), Conversion,
3094 ActingContext);
Fariborz Jahanianf4061e32009-09-14 20:41:01 +00003095 // Conversion functions to a different type in the base class is visible in
3096 // the derived class. So, a derived to base conversion should not participate
3097 // in overload resolution.
3098 if (Candidate.Conversions[0].Standard.Second == ICK_Derived_To_Base)
3099 Candidate.Conversions[0].Standard.Second = ICK_Identity;
John McCall0d1da222010-01-12 00:44:57 +00003100 if (Candidate.Conversions[0].isBad()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00003101 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003102 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00003103 return;
3104 }
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00003105
3106 // We won't go through a user-define type conversion function to convert a
3107 // derived to base as such conversions are given Conversion Rank. They only
3108 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
3109 QualType FromCanon
3110 = Context.getCanonicalType(From->getType().getUnqualifiedType());
3111 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
3112 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
3113 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00003114 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00003115 return;
3116 }
3117
Douglas Gregora1f013e2008-11-07 22:36:19 +00003118
3119 // To determine what the conversion from the result of calling the
3120 // conversion function to the type we're eventually trying to
3121 // convert to (ToType), we need to synthesize a call to the
3122 // conversion function and attempt copy initialization from it. This
3123 // makes sure that we get the right semantics with respect to
3124 // lvalues/rvalues and the type. Fortunately, we can allocate this
3125 // call on the stack and we don't need its arguments to be
3126 // well-formed.
Mike Stump11289f42009-09-09 15:08:12 +00003127 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
Douglas Gregore8f080122009-11-17 21:16:22 +00003128 From->getLocStart());
Douglas Gregora1f013e2008-11-07 22:36:19 +00003129 ImplicitCastExpr ConversionFn(Context.getPointerType(Conversion->getType()),
Eli Friedman06ed2a52009-10-20 08:27:19 +00003130 CastExpr::CK_FunctionToPointerDecay,
Douglas Gregora11693b2008-11-12 17:17:38 +00003131 &ConversionRef, false);
Mike Stump11289f42009-09-09 15:08:12 +00003132
3133 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenekd7b4f402009-02-09 20:51:47 +00003134 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
3135 // allocator).
Mike Stump11289f42009-09-09 15:08:12 +00003136 CallExpr Call(Context, &ConversionFn, 0, 0,
Douglas Gregora1f013e2008-11-07 22:36:19 +00003137 Conversion->getConversionType().getNonReferenceType(),
Douglas Gregore8f080122009-11-17 21:16:22 +00003138 From->getLocStart());
Mike Stump11289f42009-09-09 15:08:12 +00003139 ImplicitConversionSequence ICS =
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003140 TryCopyInitialization(*this, &Call, ToType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00003141 /*SuppressUserConversions=*/true,
Anders Carlsson20d13322009-08-27 17:37:39 +00003142 /*InOverloadResolution=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00003143
John McCall0d1da222010-01-12 00:44:57 +00003144 switch (ICS.getKind()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00003145 case ImplicitConversionSequence::StandardConversion:
3146 Candidate.FinalConversion = ICS.Standard;
Douglas Gregor2c326bc2010-04-12 23:42:09 +00003147
3148 // C++ [over.ics.user]p3:
3149 // If the user-defined conversion is specified by a specialization of a
3150 // conversion function template, the second standard conversion sequence
3151 // shall have exact match rank.
3152 if (Conversion->getPrimaryTemplate() &&
3153 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
3154 Candidate.Viable = false;
3155 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
3156 }
3157
Douglas Gregora1f013e2008-11-07 22:36:19 +00003158 break;
3159
3160 case ImplicitConversionSequence::BadConversion:
3161 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00003162 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00003163 break;
3164
3165 default:
Mike Stump11289f42009-09-09 15:08:12 +00003166 assert(false &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00003167 "Can only end up with a standard conversion sequence or failure");
3168 }
3169}
3170
Douglas Gregor05155d82009-08-21 23:19:43 +00003171/// \brief Adds a conversion function template specialization
3172/// candidate to the overload set, using template argument deduction
3173/// to deduce the template arguments of the conversion function
3174/// template from the type that we are converting to (C++
3175/// [temp.deduct.conv]).
Mike Stump11289f42009-09-09 15:08:12 +00003176void
Douglas Gregor05155d82009-08-21 23:19:43 +00003177Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00003178 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00003179 CXXRecordDecl *ActingDC,
Douglas Gregor05155d82009-08-21 23:19:43 +00003180 Expr *From, QualType ToType,
3181 OverloadCandidateSet &CandidateSet) {
3182 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
3183 "Only conversion function templates permitted here");
3184
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003185 if (!CandidateSet.isNewCandidate(FunctionTemplate))
3186 return;
3187
John McCallbc077cf2010-02-08 23:07:23 +00003188 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor05155d82009-08-21 23:19:43 +00003189 CXXConversionDecl *Specialization = 0;
3190 if (TemplateDeductionResult Result
Mike Stump11289f42009-09-09 15:08:12 +00003191 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor05155d82009-08-21 23:19:43 +00003192 Specialization, Info)) {
3193 // FIXME: Record what happened with template argument deduction, so
3194 // that we can give the user a beautiful diagnostic.
3195 (void)Result;
3196 return;
3197 }
Mike Stump11289f42009-09-09 15:08:12 +00003198
Douglas Gregor05155d82009-08-21 23:19:43 +00003199 // Add the conversion function template specialization produced by
3200 // template argument deduction as a candidate.
3201 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00003202 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
John McCallb89836b2010-01-26 01:37:31 +00003203 CandidateSet);
Douglas Gregor05155d82009-08-21 23:19:43 +00003204}
3205
Douglas Gregorab7897a2008-11-19 22:57:39 +00003206/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
3207/// converts the given @c Object to a function pointer via the
3208/// conversion function @c Conversion, and then attempts to call it
3209/// with the given arguments (C++ [over.call.object]p2-4). Proto is
3210/// the type of function that we'll eventually be calling.
3211void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00003212 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00003213 CXXRecordDecl *ActingContext,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003214 const FunctionProtoType *Proto,
John McCall6e9f8f62009-12-03 04:06:58 +00003215 QualType ObjectType,
3216 Expr **Args, unsigned NumArgs,
Douglas Gregorab7897a2008-11-19 22:57:39 +00003217 OverloadCandidateSet& CandidateSet) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003218 if (!CandidateSet.isNewCandidate(Conversion))
3219 return;
3220
Douglas Gregor27381f32009-11-23 12:27:39 +00003221 // Overload resolution is always an unevaluated context.
3222 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
3223
Douglas Gregorab7897a2008-11-19 22:57:39 +00003224 CandidateSet.push_back(OverloadCandidate());
3225 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003226 Candidate.FoundDecl = FoundDecl;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003227 Candidate.Function = 0;
3228 Candidate.Surrogate = Conversion;
3229 Candidate.Viable = true;
3230 Candidate.IsSurrogate = true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003231 Candidate.IgnoreObjectArgument = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003232 Candidate.Conversions.resize(NumArgs + 1);
3233
3234 // Determine the implicit conversion sequence for the implicit
3235 // object parameter.
Mike Stump11289f42009-09-09 15:08:12 +00003236 ImplicitConversionSequence ObjectInit
John McCall6e9f8f62009-12-03 04:06:58 +00003237 = TryObjectArgumentInitialization(ObjectType, Conversion, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00003238 if (ObjectInit.isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00003239 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003240 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCallfe796dd2010-01-23 05:17:32 +00003241 Candidate.Conversions[0] = ObjectInit;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003242 return;
3243 }
3244
3245 // The first conversion is actually a user-defined conversion whose
3246 // first conversion is ObjectInit's standard conversion (which is
3247 // effectively a reference binding). Record it as such.
John McCall0d1da222010-01-12 00:44:57 +00003248 Candidate.Conversions[0].setUserDefined();
Douglas Gregorab7897a2008-11-19 22:57:39 +00003249 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00003250 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003251 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
Mike Stump11289f42009-09-09 15:08:12 +00003252 Candidate.Conversions[0].UserDefined.After
Douglas Gregorab7897a2008-11-19 22:57:39 +00003253 = Candidate.Conversions[0].UserDefined.Before;
3254 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
3255
Mike Stump11289f42009-09-09 15:08:12 +00003256 // Find the
Douglas Gregorab7897a2008-11-19 22:57:39 +00003257 unsigned NumArgsInProto = Proto->getNumArgs();
3258
3259 // (C++ 13.3.2p2): A candidate function having fewer than m
3260 // parameters is viable only if it has an ellipsis in its parameter
3261 // list (8.3.5).
3262 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
3263 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003264 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003265 return;
3266 }
3267
3268 // Function types don't have any default arguments, so just check if
3269 // we have enough arguments.
3270 if (NumArgs < NumArgsInProto) {
3271 // Not enough arguments.
3272 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003273 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003274 return;
3275 }
3276
3277 // Determine the implicit conversion sequences for each of the
3278 // arguments.
3279 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
3280 if (ArgIdx < NumArgsInProto) {
3281 // (C++ 13.3.2p3): for F to be a viable function, there shall
3282 // exist for each argument an implicit conversion sequence
3283 // (13.3.3.1) that converts that argument to the corresponding
3284 // parameter of F.
3285 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00003286 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003287 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00003288 /*SuppressUserConversions=*/false,
Anders Carlsson20d13322009-08-27 17:37:39 +00003289 /*InOverloadResolution=*/false);
John McCall0d1da222010-01-12 00:44:57 +00003290 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00003291 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003292 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003293 break;
3294 }
3295 } else {
3296 // (C++ 13.3.2p2): For the purposes of overload resolution, any
3297 // argument for which there is no corresponding parameter is
3298 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00003299 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregorab7897a2008-11-19 22:57:39 +00003300 }
3301 }
3302}
3303
Mike Stump87c57ac2009-05-16 07:39:55 +00003304// FIXME: This will eventually be removed, once we've migrated all of the
3305// operator overloading logic over to the scheme used by binary operators, which
3306// works for template instantiation.
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003307void Sema::AddOperatorCandidates(OverloadedOperatorKind Op, Scope *S,
Douglas Gregor94eabf32009-02-04 16:44:47 +00003308 SourceLocation OpLoc,
Douglas Gregor436424c2008-11-18 23:14:02 +00003309 Expr **Args, unsigned NumArgs,
Douglas Gregor94eabf32009-02-04 16:44:47 +00003310 OverloadCandidateSet& CandidateSet,
3311 SourceRange OpRange) {
John McCall4c4c1df2010-01-26 03:27:55 +00003312 UnresolvedSet<16> Fns;
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003313
3314 QualType T1 = Args[0]->getType();
3315 QualType T2;
3316 if (NumArgs > 1)
3317 T2 = Args[1]->getType();
3318
3319 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00003320 if (S)
John McCall4c4c1df2010-01-26 03:27:55 +00003321 LookupOverloadedOperatorName(Op, S, T1, T2, Fns);
3322 AddFunctionCandidates(Fns, Args, NumArgs, CandidateSet, false);
3323 AddArgumentDependentLookupCandidates(OpName, false, Args, NumArgs, 0,
3324 CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003325 AddMemberOperatorCandidates(Op, OpLoc, Args, NumArgs, CandidateSet, OpRange);
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003326 AddBuiltinOperatorCandidates(Op, OpLoc, Args, NumArgs, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003327}
3328
3329/// \brief Add overload candidates for overloaded operators that are
3330/// member functions.
3331///
3332/// Add the overloaded operator candidates that are member functions
3333/// for the operator Op that was used in an operator expression such
3334/// as "x Op y". , Args/NumArgs provides the operator arguments, and
3335/// CandidateSet will store the added overload candidates. (C++
3336/// [over.match.oper]).
3337void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
3338 SourceLocation OpLoc,
3339 Expr **Args, unsigned NumArgs,
3340 OverloadCandidateSet& CandidateSet,
3341 SourceRange OpRange) {
Douglas Gregor436424c2008-11-18 23:14:02 +00003342 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
3343
3344 // C++ [over.match.oper]p3:
3345 // For a unary operator @ with an operand of a type whose
3346 // cv-unqualified version is T1, and for a binary operator @ with
3347 // a left operand of a type whose cv-unqualified version is T1 and
3348 // a right operand of a type whose cv-unqualified version is T2,
3349 // three sets of candidate functions, designated member
3350 // candidates, non-member candidates and built-in candidates, are
3351 // constructed as follows:
3352 QualType T1 = Args[0]->getType();
3353 QualType T2;
3354 if (NumArgs > 1)
3355 T2 = Args[1]->getType();
3356
3357 // -- If T1 is a class type, the set of member candidates is the
3358 // result of the qualified lookup of T1::operator@
3359 // (13.3.1.1.1); otherwise, the set of member candidates is
3360 // empty.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003361 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor6a1f9652009-08-27 23:35:55 +00003362 // Complete the type if it can be completed. Otherwise, we're done.
Anders Carlsson7f84ed92009-10-09 23:51:55 +00003363 if (RequireCompleteType(OpLoc, T1, PDiag()))
Douglas Gregor6a1f9652009-08-27 23:35:55 +00003364 return;
Mike Stump11289f42009-09-09 15:08:12 +00003365
John McCall27b18f82009-11-17 02:14:36 +00003366 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
3367 LookupQualifiedName(Operators, T1Rec->getDecl());
3368 Operators.suppressDiagnostics();
3369
Mike Stump11289f42009-09-09 15:08:12 +00003370 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor6a1f9652009-08-27 23:35:55 +00003371 OperEnd = Operators.end();
3372 Oper != OperEnd;
John McCallf0f1cf02009-11-17 07:50:12 +00003373 ++Oper)
John McCalla0296f72010-03-19 07:35:19 +00003374 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
John McCall6e9f8f62009-12-03 04:06:58 +00003375 Args + 1, NumArgs - 1, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00003376 /* SuppressUserConversions = */ false);
Douglas Gregor436424c2008-11-18 23:14:02 +00003377 }
Douglas Gregor436424c2008-11-18 23:14:02 +00003378}
3379
Douglas Gregora11693b2008-11-12 17:17:38 +00003380/// AddBuiltinCandidate - Add a candidate for a built-in
3381/// operator. ResultTy and ParamTys are the result and parameter types
3382/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorc5e61072009-01-13 00:52:54 +00003383/// arguments being passed to the candidate. IsAssignmentOperator
3384/// should be true when this built-in candidate is an assignment
Douglas Gregor5fb53972009-01-14 15:45:31 +00003385/// operator. NumContextualBoolArguments is the number of arguments
3386/// (at the beginning of the argument list) that will be contextually
3387/// converted to bool.
Mike Stump11289f42009-09-09 15:08:12 +00003388void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregora11693b2008-11-12 17:17:38 +00003389 Expr **Args, unsigned NumArgs,
Douglas Gregorc5e61072009-01-13 00:52:54 +00003390 OverloadCandidateSet& CandidateSet,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003391 bool IsAssignmentOperator,
3392 unsigned NumContextualBoolArguments) {
Douglas Gregor27381f32009-11-23 12:27:39 +00003393 // Overload resolution is always an unevaluated context.
3394 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
3395
Douglas Gregora11693b2008-11-12 17:17:38 +00003396 // Add this candidate
3397 CandidateSet.push_back(OverloadCandidate());
3398 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003399 Candidate.FoundDecl = DeclAccessPair::make(0, AS_none);
Douglas Gregora11693b2008-11-12 17:17:38 +00003400 Candidate.Function = 0;
Douglas Gregor1d248c52008-12-12 02:00:36 +00003401 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003402 Candidate.IgnoreObjectArgument = false;
Douglas Gregora11693b2008-11-12 17:17:38 +00003403 Candidate.BuiltinTypes.ResultTy = ResultTy;
3404 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
3405 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
3406
3407 // Determine the implicit conversion sequences for each of the
3408 // arguments.
3409 Candidate.Viable = true;
3410 Candidate.Conversions.resize(NumArgs);
3411 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregorc5e61072009-01-13 00:52:54 +00003412 // C++ [over.match.oper]p4:
3413 // For the built-in assignment operators, conversions of the
3414 // left operand are restricted as follows:
3415 // -- no temporaries are introduced to hold the left operand, and
3416 // -- no user-defined conversions are applied to the left
3417 // operand to achieve a type match with the left-most
Mike Stump11289f42009-09-09 15:08:12 +00003418 // parameter of a built-in candidate.
Douglas Gregorc5e61072009-01-13 00:52:54 +00003419 //
3420 // We block these conversions by turning off user-defined
3421 // conversions, since that is the only way that initialization of
3422 // a reference to a non-class type can occur from something that
3423 // is not of the same type.
Douglas Gregor5fb53972009-01-14 15:45:31 +00003424 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump11289f42009-09-09 15:08:12 +00003425 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor5fb53972009-01-14 15:45:31 +00003426 "Contextual conversion to bool requires bool type");
3427 Candidate.Conversions[ArgIdx] = TryContextuallyConvertToBool(Args[ArgIdx]);
3428 } else {
Mike Stump11289f42009-09-09 15:08:12 +00003429 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003430 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlsson03068aa2009-08-27 17:18:13 +00003431 ArgIdx == 0 && IsAssignmentOperator,
Anders Carlsson20d13322009-08-27 17:37:39 +00003432 /*InOverloadResolution=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00003433 }
John McCall0d1da222010-01-12 00:44:57 +00003434 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00003435 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003436 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00003437 break;
3438 }
Douglas Gregora11693b2008-11-12 17:17:38 +00003439 }
3440}
3441
3442/// BuiltinCandidateTypeSet - A set of types that will be used for the
3443/// candidate operator functions for built-in operators (C++
3444/// [over.built]). The types are separated into pointer types and
3445/// enumeration types.
3446class BuiltinCandidateTypeSet {
3447 /// TypeSet - A set of types.
Chris Lattnera59a3e22009-03-29 00:04:01 +00003448 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregora11693b2008-11-12 17:17:38 +00003449
3450 /// PointerTypes - The set of pointer types that will be used in the
3451 /// built-in candidates.
3452 TypeSet PointerTypes;
3453
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003454 /// MemberPointerTypes - The set of member pointer types that will be
3455 /// used in the built-in candidates.
3456 TypeSet MemberPointerTypes;
3457
Douglas Gregora11693b2008-11-12 17:17:38 +00003458 /// EnumerationTypes - The set of enumeration types that will be
3459 /// used in the built-in candidates.
3460 TypeSet EnumerationTypes;
3461
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003462 /// Sema - The semantic analysis instance where we are building the
3463 /// candidate type set.
3464 Sema &SemaRef;
Mike Stump11289f42009-09-09 15:08:12 +00003465
Douglas Gregora11693b2008-11-12 17:17:38 +00003466 /// Context - The AST context in which we will build the type sets.
3467 ASTContext &Context;
3468
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003469 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
3470 const Qualifiers &VisibleQuals);
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003471 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00003472
3473public:
3474 /// iterator - Iterates through the types that are part of the set.
Chris Lattnera59a3e22009-03-29 00:04:01 +00003475 typedef TypeSet::iterator iterator;
Douglas Gregora11693b2008-11-12 17:17:38 +00003476
Mike Stump11289f42009-09-09 15:08:12 +00003477 BuiltinCandidateTypeSet(Sema &SemaRef)
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003478 : SemaRef(SemaRef), Context(SemaRef.Context) { }
Douglas Gregora11693b2008-11-12 17:17:38 +00003479
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003480 void AddTypesConvertedFrom(QualType Ty,
3481 SourceLocation Loc,
3482 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003483 bool AllowExplicitConversions,
3484 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00003485
3486 /// pointer_begin - First pointer type found;
3487 iterator pointer_begin() { return PointerTypes.begin(); }
3488
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003489 /// pointer_end - Past the last pointer type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00003490 iterator pointer_end() { return PointerTypes.end(); }
3491
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003492 /// member_pointer_begin - First member pointer type found;
3493 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
3494
3495 /// member_pointer_end - Past the last member pointer type found;
3496 iterator member_pointer_end() { return MemberPointerTypes.end(); }
3497
Douglas Gregora11693b2008-11-12 17:17:38 +00003498 /// enumeration_begin - First enumeration type found;
3499 iterator enumeration_begin() { return EnumerationTypes.begin(); }
3500
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003501 /// enumeration_end - Past the last enumeration type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00003502 iterator enumeration_end() { return EnumerationTypes.end(); }
3503};
3504
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003505/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregora11693b2008-11-12 17:17:38 +00003506/// the set of pointer types along with any more-qualified variants of
3507/// that type. For example, if @p Ty is "int const *", this routine
3508/// will add "int const *", "int const volatile *", "int const
3509/// restrict *", and "int const volatile restrict *" to the set of
3510/// pointer types. Returns true if the add of @p Ty itself succeeded,
3511/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00003512///
3513/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003514bool
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003515BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
3516 const Qualifiers &VisibleQuals) {
John McCall8ccfcb52009-09-24 19:53:00 +00003517
Douglas Gregora11693b2008-11-12 17:17:38 +00003518 // Insert this type.
Chris Lattnera59a3e22009-03-29 00:04:01 +00003519 if (!PointerTypes.insert(Ty))
Douglas Gregora11693b2008-11-12 17:17:38 +00003520 return false;
3521
John McCall8ccfcb52009-09-24 19:53:00 +00003522 const PointerType *PointerTy = Ty->getAs<PointerType>();
3523 assert(PointerTy && "type was not a pointer type!");
Douglas Gregora11693b2008-11-12 17:17:38 +00003524
John McCall8ccfcb52009-09-24 19:53:00 +00003525 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00003526 // Don't add qualified variants of arrays. For one, they're not allowed
3527 // (the qualifier would sink to the element type), and for another, the
3528 // only overload situation where it matters is subscript or pointer +- int,
3529 // and those shouldn't have qualifier variants anyway.
3530 if (PointeeTy->isArrayType())
3531 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00003532 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Douglas Gregor4ef1d402009-11-09 22:08:55 +00003533 if (const ConstantArrayType *Array =Context.getAsConstantArrayType(PointeeTy))
Fariborz Jahanianfacfdd42009-11-09 21:02:05 +00003534 BaseCVR = Array->getElementType().getCVRQualifiers();
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003535 bool hasVolatile = VisibleQuals.hasVolatile();
3536 bool hasRestrict = VisibleQuals.hasRestrict();
3537
John McCall8ccfcb52009-09-24 19:53:00 +00003538 // Iterate through all strict supersets of BaseCVR.
3539 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
3540 if ((CVR | BaseCVR) != CVR) continue;
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003541 // Skip over Volatile/Restrict if no Volatile/Restrict found anywhere
3542 // in the types.
3543 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
3544 if ((CVR & Qualifiers::Restrict) && !hasRestrict) continue;
John McCall8ccfcb52009-09-24 19:53:00 +00003545 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
3546 PointerTypes.insert(Context.getPointerType(QPointeeTy));
Douglas Gregora11693b2008-11-12 17:17:38 +00003547 }
3548
3549 return true;
3550}
3551
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003552/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
3553/// to the set of pointer types along with any more-qualified variants of
3554/// that type. For example, if @p Ty is "int const *", this routine
3555/// will add "int const *", "int const volatile *", "int const
3556/// restrict *", and "int const volatile restrict *" to the set of
3557/// pointer types. Returns true if the add of @p Ty itself succeeded,
3558/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00003559///
3560/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003561bool
3562BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
3563 QualType Ty) {
3564 // Insert this type.
3565 if (!MemberPointerTypes.insert(Ty))
3566 return false;
3567
John McCall8ccfcb52009-09-24 19:53:00 +00003568 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
3569 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003570
John McCall8ccfcb52009-09-24 19:53:00 +00003571 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00003572 // Don't add qualified variants of arrays. For one, they're not allowed
3573 // (the qualifier would sink to the element type), and for another, the
3574 // only overload situation where it matters is subscript or pointer +- int,
3575 // and those shouldn't have qualifier variants anyway.
3576 if (PointeeTy->isArrayType())
3577 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00003578 const Type *ClassTy = PointerTy->getClass();
3579
3580 // Iterate through all strict supersets of the pointee type's CVR
3581 // qualifiers.
3582 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
3583 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
3584 if ((CVR | BaseCVR) != CVR) continue;
3585
3586 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
3587 MemberPointerTypes.insert(Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003588 }
3589
3590 return true;
3591}
3592
Douglas Gregora11693b2008-11-12 17:17:38 +00003593/// AddTypesConvertedFrom - Add each of the types to which the type @p
3594/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003595/// primarily interested in pointer types and enumeration types. We also
3596/// take member pointer types, for the conditional operator.
Douglas Gregor5fb53972009-01-14 15:45:31 +00003597/// AllowUserConversions is true if we should look at the conversion
3598/// functions of a class type, and AllowExplicitConversions if we
3599/// should also include the explicit conversion functions of a class
3600/// type.
Mike Stump11289f42009-09-09 15:08:12 +00003601void
Douglas Gregor5fb53972009-01-14 15:45:31 +00003602BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003603 SourceLocation Loc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003604 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003605 bool AllowExplicitConversions,
3606 const Qualifiers &VisibleQuals) {
Douglas Gregora11693b2008-11-12 17:17:38 +00003607 // Only deal with canonical types.
3608 Ty = Context.getCanonicalType(Ty);
3609
3610 // Look through reference types; they aren't part of the type of an
3611 // expression for the purposes of conversions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003612 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregora11693b2008-11-12 17:17:38 +00003613 Ty = RefTy->getPointeeType();
3614
3615 // We don't care about qualifiers on the type.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003616 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +00003617
Sebastian Redl65ae2002009-11-05 16:36:20 +00003618 // If we're dealing with an array type, decay to the pointer.
3619 if (Ty->isArrayType())
3620 Ty = SemaRef.Context.getArrayDecayedType(Ty);
3621
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003622 if (const PointerType *PointerTy = Ty->getAs<PointerType>()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00003623 QualType PointeeTy = PointerTy->getPointeeType();
3624
3625 // Insert our type, and its more-qualified variants, into the set
3626 // of types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003627 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregora11693b2008-11-12 17:17:38 +00003628 return;
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003629 } else if (Ty->isMemberPointerType()) {
3630 // Member pointers are far easier, since the pointee can't be converted.
3631 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
3632 return;
Douglas Gregora11693b2008-11-12 17:17:38 +00003633 } else if (Ty->isEnumeralType()) {
Chris Lattnera59a3e22009-03-29 00:04:01 +00003634 EnumerationTypes.insert(Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00003635 } else if (AllowUserConversions) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003636 if (const RecordType *TyRec = Ty->getAs<RecordType>()) {
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003637 if (SemaRef.RequireCompleteType(Loc, Ty, 0)) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003638 // No conversion functions in incomplete types.
3639 return;
3640 }
Mike Stump11289f42009-09-09 15:08:12 +00003641
Douglas Gregora11693b2008-11-12 17:17:38 +00003642 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCallad371252010-01-20 00:46:10 +00003643 const UnresolvedSetImpl *Conversions
Fariborz Jahanianae01f782009-10-07 17:26:09 +00003644 = ClassDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00003645 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00003646 E = Conversions->end(); I != E; ++I) {
John McCallda4458e2010-03-31 01:36:47 +00003647 NamedDecl *D = I.getDecl();
3648 if (isa<UsingShadowDecl>(D))
3649 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor05155d82009-08-21 23:19:43 +00003650
Mike Stump11289f42009-09-09 15:08:12 +00003651 // Skip conversion function templates; they don't tell us anything
Douglas Gregor05155d82009-08-21 23:19:43 +00003652 // about which builtin types we can convert to.
John McCallda4458e2010-03-31 01:36:47 +00003653 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor05155d82009-08-21 23:19:43 +00003654 continue;
3655
John McCallda4458e2010-03-31 01:36:47 +00003656 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003657 if (AllowExplicitConversions || !Conv->isExplicit()) {
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003658 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003659 VisibleQuals);
3660 }
Douglas Gregora11693b2008-11-12 17:17:38 +00003661 }
3662 }
3663 }
3664}
3665
Douglas Gregor84605ae2009-08-24 13:43:27 +00003666/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
3667/// the volatile- and non-volatile-qualified assignment operators for the
3668/// given type to the candidate set.
3669static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
3670 QualType T,
Mike Stump11289f42009-09-09 15:08:12 +00003671 Expr **Args,
Douglas Gregor84605ae2009-08-24 13:43:27 +00003672 unsigned NumArgs,
3673 OverloadCandidateSet &CandidateSet) {
3674 QualType ParamTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00003675
Douglas Gregor84605ae2009-08-24 13:43:27 +00003676 // T& operator=(T&, T)
3677 ParamTypes[0] = S.Context.getLValueReferenceType(T);
3678 ParamTypes[1] = T;
3679 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3680 /*IsAssignmentOperator=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00003681
Douglas Gregor84605ae2009-08-24 13:43:27 +00003682 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
3683 // volatile T& operator=(volatile T&, T)
John McCall8ccfcb52009-09-24 19:53:00 +00003684 ParamTypes[0]
3685 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor84605ae2009-08-24 13:43:27 +00003686 ParamTypes[1] = T;
3687 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00003688 /*IsAssignmentOperator=*/true);
Douglas Gregor84605ae2009-08-24 13:43:27 +00003689 }
3690}
Mike Stump11289f42009-09-09 15:08:12 +00003691
Sebastian Redl1054fae2009-10-25 17:03:50 +00003692/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
3693/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003694static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
3695 Qualifiers VRQuals;
3696 const RecordType *TyRec;
3697 if (const MemberPointerType *RHSMPType =
3698 ArgExpr->getType()->getAs<MemberPointerType>())
3699 TyRec = cast<RecordType>(RHSMPType->getClass());
3700 else
3701 TyRec = ArgExpr->getType()->getAs<RecordType>();
3702 if (!TyRec) {
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003703 // Just to be safe, assume the worst case.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003704 VRQuals.addVolatile();
3705 VRQuals.addRestrict();
3706 return VRQuals;
3707 }
3708
3709 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall67da35c2010-02-04 22:26:26 +00003710 if (!ClassDecl->hasDefinition())
3711 return VRQuals;
3712
John McCallad371252010-01-20 00:46:10 +00003713 const UnresolvedSetImpl *Conversions =
Sebastian Redl1054fae2009-10-25 17:03:50 +00003714 ClassDecl->getVisibleConversionFunctions();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003715
John McCallad371252010-01-20 00:46:10 +00003716 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00003717 E = Conversions->end(); I != E; ++I) {
John McCallda4458e2010-03-31 01:36:47 +00003718 NamedDecl *D = I.getDecl();
3719 if (isa<UsingShadowDecl>(D))
3720 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3721 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003722 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
3723 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
3724 CanTy = ResTypeRef->getPointeeType();
3725 // Need to go down the pointer/mempointer chain and add qualifiers
3726 // as see them.
3727 bool done = false;
3728 while (!done) {
3729 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
3730 CanTy = ResTypePtr->getPointeeType();
3731 else if (const MemberPointerType *ResTypeMPtr =
3732 CanTy->getAs<MemberPointerType>())
3733 CanTy = ResTypeMPtr->getPointeeType();
3734 else
3735 done = true;
3736 if (CanTy.isVolatileQualified())
3737 VRQuals.addVolatile();
3738 if (CanTy.isRestrictQualified())
3739 VRQuals.addRestrict();
3740 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
3741 return VRQuals;
3742 }
3743 }
3744 }
3745 return VRQuals;
3746}
3747
Douglas Gregord08452f2008-11-19 15:42:04 +00003748/// AddBuiltinOperatorCandidates - Add the appropriate built-in
3749/// operator overloads to the candidate set (C++ [over.built]), based
3750/// on the operator @p Op and the arguments given. For example, if the
3751/// operator is a binary '+', this routine might add "int
3752/// operator+(int, int)" to cover integer addition.
Douglas Gregora11693b2008-11-12 17:17:38 +00003753void
Mike Stump11289f42009-09-09 15:08:12 +00003754Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003755 SourceLocation OpLoc,
Douglas Gregord08452f2008-11-19 15:42:04 +00003756 Expr **Args, unsigned NumArgs,
3757 OverloadCandidateSet& CandidateSet) {
Douglas Gregora11693b2008-11-12 17:17:38 +00003758 // The set of "promoted arithmetic types", which are the arithmetic
3759 // types are that preserved by promotion (C++ [over.built]p2). Note
3760 // that the first few of these types are the promoted integral
3761 // types; these types need to be first.
3762 // FIXME: What about complex?
3763 const unsigned FirstIntegralType = 0;
3764 const unsigned LastIntegralType = 13;
Mike Stump11289f42009-09-09 15:08:12 +00003765 const unsigned FirstPromotedIntegralType = 7,
Douglas Gregora11693b2008-11-12 17:17:38 +00003766 LastPromotedIntegralType = 13;
3767 const unsigned FirstPromotedArithmeticType = 7,
3768 LastPromotedArithmeticType = 16;
3769 const unsigned NumArithmeticTypes = 16;
3770 QualType ArithmeticTypes[NumArithmeticTypes] = {
Mike Stump11289f42009-09-09 15:08:12 +00003771 Context.BoolTy, Context.CharTy, Context.WCharTy,
3772// FIXME: Context.Char16Ty, Context.Char32Ty,
Douglas Gregora11693b2008-11-12 17:17:38 +00003773 Context.SignedCharTy, Context.ShortTy,
3774 Context.UnsignedCharTy, Context.UnsignedShortTy,
3775 Context.IntTy, Context.LongTy, Context.LongLongTy,
3776 Context.UnsignedIntTy, Context.UnsignedLongTy, Context.UnsignedLongLongTy,
3777 Context.FloatTy, Context.DoubleTy, Context.LongDoubleTy
3778 };
Douglas Gregorb8440a72009-10-21 22:01:30 +00003779 assert(ArithmeticTypes[FirstPromotedIntegralType] == Context.IntTy &&
3780 "Invalid first promoted integral type");
3781 assert(ArithmeticTypes[LastPromotedIntegralType - 1]
3782 == Context.UnsignedLongLongTy &&
3783 "Invalid last promoted integral type");
3784 assert(ArithmeticTypes[FirstPromotedArithmeticType] == Context.IntTy &&
3785 "Invalid first promoted arithmetic type");
3786 assert(ArithmeticTypes[LastPromotedArithmeticType - 1]
3787 == Context.LongDoubleTy &&
3788 "Invalid last promoted arithmetic type");
3789
Douglas Gregora11693b2008-11-12 17:17:38 +00003790 // Find all of the types that the arguments can convert to, but only
3791 // if the operator we're looking at has built-in operator candidates
3792 // that make use of these types.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003793 Qualifiers VisibleTypeConversionsQuals;
3794 VisibleTypeConversionsQuals.addConst();
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00003795 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
3796 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
3797
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003798 BuiltinCandidateTypeSet CandidateTypes(*this);
Douglas Gregora11693b2008-11-12 17:17:38 +00003799 if (Op == OO_Less || Op == OO_Greater || Op == OO_LessEqual ||
3800 Op == OO_GreaterEqual || Op == OO_EqualEqual || Op == OO_ExclaimEqual ||
Douglas Gregord08452f2008-11-19 15:42:04 +00003801 Op == OO_Plus || (Op == OO_Minus && NumArgs == 2) || Op == OO_Equal ||
Douglas Gregora11693b2008-11-12 17:17:38 +00003802 Op == OO_PlusEqual || Op == OO_MinusEqual || Op == OO_Subscript ||
Douglas Gregord08452f2008-11-19 15:42:04 +00003803 Op == OO_ArrowStar || Op == OO_PlusPlus || Op == OO_MinusMinus ||
Sebastian Redl1a99f442009-04-16 17:51:27 +00003804 (Op == OO_Star && NumArgs == 1) || Op == OO_Conditional) {
Douglas Gregord08452f2008-11-19 15:42:04 +00003805 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Douglas Gregor5fb53972009-01-14 15:45:31 +00003806 CandidateTypes.AddTypesConvertedFrom(Args[ArgIdx]->getType(),
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003807 OpLoc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003808 true,
3809 (Op == OO_Exclaim ||
3810 Op == OO_AmpAmp ||
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003811 Op == OO_PipePipe),
3812 VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00003813 }
3814
3815 bool isComparison = false;
3816 switch (Op) {
3817 case OO_None:
3818 case NUM_OVERLOADED_OPERATORS:
3819 assert(false && "Expected an overloaded operator");
3820 break;
3821
Douglas Gregord08452f2008-11-19 15:42:04 +00003822 case OO_Star: // '*' is either unary or binary
Mike Stump11289f42009-09-09 15:08:12 +00003823 if (NumArgs == 1)
Douglas Gregord08452f2008-11-19 15:42:04 +00003824 goto UnaryStar;
3825 else
3826 goto BinaryStar;
3827 break;
3828
3829 case OO_Plus: // '+' is either unary or binary
3830 if (NumArgs == 1)
3831 goto UnaryPlus;
3832 else
3833 goto BinaryPlus;
3834 break;
3835
3836 case OO_Minus: // '-' is either unary or binary
3837 if (NumArgs == 1)
3838 goto UnaryMinus;
3839 else
3840 goto BinaryMinus;
3841 break;
3842
3843 case OO_Amp: // '&' is either unary or binary
3844 if (NumArgs == 1)
3845 goto UnaryAmp;
3846 else
3847 goto BinaryAmp;
3848
3849 case OO_PlusPlus:
3850 case OO_MinusMinus:
3851 // C++ [over.built]p3:
3852 //
3853 // For every pair (T, VQ), where T is an arithmetic type, and VQ
3854 // is either volatile or empty, there exist candidate operator
3855 // functions of the form
3856 //
3857 // VQ T& operator++(VQ T&);
3858 // T operator++(VQ T&, int);
3859 //
3860 // C++ [over.built]p4:
3861 //
3862 // For every pair (T, VQ), where T is an arithmetic type other
3863 // than bool, and VQ is either volatile or empty, there exist
3864 // candidate operator functions of the form
3865 //
3866 // VQ T& operator--(VQ T&);
3867 // T operator--(VQ T&, int);
Mike Stump11289f42009-09-09 15:08:12 +00003868 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
Douglas Gregord08452f2008-11-19 15:42:04 +00003869 Arith < NumArithmeticTypes; ++Arith) {
3870 QualType ArithTy = ArithmeticTypes[Arith];
Mike Stump11289f42009-09-09 15:08:12 +00003871 QualType ParamTypes[2]
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003872 = { Context.getLValueReferenceType(ArithTy), Context.IntTy };
Douglas Gregord08452f2008-11-19 15:42:04 +00003873
3874 // Non-volatile version.
3875 if (NumArgs == 1)
3876 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3877 else
3878 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003879 // heuristic to reduce number of builtin candidates in the set.
3880 // Add volatile version only if there are conversions to a volatile type.
3881 if (VisibleTypeConversionsQuals.hasVolatile()) {
3882 // Volatile version
3883 ParamTypes[0]
3884 = Context.getLValueReferenceType(Context.getVolatileType(ArithTy));
3885 if (NumArgs == 1)
3886 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3887 else
3888 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
3889 }
Douglas Gregord08452f2008-11-19 15:42:04 +00003890 }
3891
3892 // C++ [over.built]p5:
3893 //
3894 // For every pair (T, VQ), where T is a cv-qualified or
3895 // cv-unqualified object type, and VQ is either volatile or
3896 // empty, there exist candidate operator functions of the form
3897 //
3898 // T*VQ& operator++(T*VQ&);
3899 // T*VQ& operator--(T*VQ&);
3900 // T* operator++(T*VQ&, int);
3901 // T* operator--(T*VQ&, int);
3902 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3903 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3904 // Skip pointer types that aren't pointers to object types.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003905 if (!(*Ptr)->getAs<PointerType>()->getPointeeType()->isObjectType())
Douglas Gregord08452f2008-11-19 15:42:04 +00003906 continue;
3907
Mike Stump11289f42009-09-09 15:08:12 +00003908 QualType ParamTypes[2] = {
3909 Context.getLValueReferenceType(*Ptr), Context.IntTy
Douglas Gregord08452f2008-11-19 15:42:04 +00003910 };
Mike Stump11289f42009-09-09 15:08:12 +00003911
Douglas Gregord08452f2008-11-19 15:42:04 +00003912 // Without volatile
3913 if (NumArgs == 1)
3914 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3915 else
3916 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3917
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003918 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
3919 VisibleTypeConversionsQuals.hasVolatile()) {
Douglas Gregord08452f2008-11-19 15:42:04 +00003920 // With volatile
John McCall8ccfcb52009-09-24 19:53:00 +00003921 ParamTypes[0]
3922 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregord08452f2008-11-19 15:42:04 +00003923 if (NumArgs == 1)
3924 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3925 else
3926 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3927 }
3928 }
3929 break;
3930
3931 UnaryStar:
3932 // C++ [over.built]p6:
3933 // For every cv-qualified or cv-unqualified object type T, there
3934 // exist candidate operator functions of the form
3935 //
3936 // T& operator*(T*);
3937 //
3938 // C++ [over.built]p7:
3939 // For every function type T, there exist candidate operator
3940 // functions of the form
3941 // T& operator*(T*);
3942 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3943 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3944 QualType ParamTy = *Ptr;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003945 QualType PointeeTy = ParamTy->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00003946 AddBuiltinCandidate(Context.getLValueReferenceType(PointeeTy),
Douglas Gregord08452f2008-11-19 15:42:04 +00003947 &ParamTy, Args, 1, CandidateSet);
3948 }
3949 break;
3950
3951 UnaryPlus:
3952 // C++ [over.built]p8:
3953 // For every type T, there exist candidate operator functions of
3954 // the form
3955 //
3956 // T* operator+(T*);
3957 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3958 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3959 QualType ParamTy = *Ptr;
3960 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
3961 }
Mike Stump11289f42009-09-09 15:08:12 +00003962
Douglas Gregord08452f2008-11-19 15:42:04 +00003963 // Fall through
3964
3965 UnaryMinus:
3966 // C++ [over.built]p9:
3967 // For every promoted arithmetic type T, there exist candidate
3968 // operator functions of the form
3969 //
3970 // T operator+(T);
3971 // T operator-(T);
Mike Stump11289f42009-09-09 15:08:12 +00003972 for (unsigned Arith = FirstPromotedArithmeticType;
Douglas Gregord08452f2008-11-19 15:42:04 +00003973 Arith < LastPromotedArithmeticType; ++Arith) {
3974 QualType ArithTy = ArithmeticTypes[Arith];
3975 AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
3976 }
3977 break;
3978
3979 case OO_Tilde:
3980 // C++ [over.built]p10:
3981 // For every promoted integral type T, there exist candidate
3982 // operator functions of the form
3983 //
3984 // T operator~(T);
Mike Stump11289f42009-09-09 15:08:12 +00003985 for (unsigned Int = FirstPromotedIntegralType;
Douglas Gregord08452f2008-11-19 15:42:04 +00003986 Int < LastPromotedIntegralType; ++Int) {
3987 QualType IntTy = ArithmeticTypes[Int];
3988 AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
3989 }
3990 break;
3991
Douglas Gregora11693b2008-11-12 17:17:38 +00003992 case OO_New:
3993 case OO_Delete:
3994 case OO_Array_New:
3995 case OO_Array_Delete:
Douglas Gregora11693b2008-11-12 17:17:38 +00003996 case OO_Call:
Douglas Gregord08452f2008-11-19 15:42:04 +00003997 assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
Douglas Gregora11693b2008-11-12 17:17:38 +00003998 break;
3999
4000 case OO_Comma:
Douglas Gregord08452f2008-11-19 15:42:04 +00004001 UnaryAmp:
4002 case OO_Arrow:
Douglas Gregora11693b2008-11-12 17:17:38 +00004003 // C++ [over.match.oper]p3:
4004 // -- For the operator ',', the unary operator '&', or the
4005 // operator '->', the built-in candidates set is empty.
Douglas Gregora11693b2008-11-12 17:17:38 +00004006 break;
4007
Douglas Gregor84605ae2009-08-24 13:43:27 +00004008 case OO_EqualEqual:
4009 case OO_ExclaimEqual:
4010 // C++ [over.match.oper]p16:
Mike Stump11289f42009-09-09 15:08:12 +00004011 // For every pointer to member type T, there exist candidate operator
4012 // functions of the form
Douglas Gregor84605ae2009-08-24 13:43:27 +00004013 //
4014 // bool operator==(T,T);
4015 // bool operator!=(T,T);
Mike Stump11289f42009-09-09 15:08:12 +00004016 for (BuiltinCandidateTypeSet::iterator
Douglas Gregor84605ae2009-08-24 13:43:27 +00004017 MemPtr = CandidateTypes.member_pointer_begin(),
4018 MemPtrEnd = CandidateTypes.member_pointer_end();
4019 MemPtr != MemPtrEnd;
4020 ++MemPtr) {
4021 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
4022 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
4023 }
Mike Stump11289f42009-09-09 15:08:12 +00004024
Douglas Gregor84605ae2009-08-24 13:43:27 +00004025 // Fall through
Mike Stump11289f42009-09-09 15:08:12 +00004026
Douglas Gregora11693b2008-11-12 17:17:38 +00004027 case OO_Less:
4028 case OO_Greater:
4029 case OO_LessEqual:
4030 case OO_GreaterEqual:
Douglas Gregora11693b2008-11-12 17:17:38 +00004031 // C++ [over.built]p15:
4032 //
4033 // For every pointer or enumeration type T, there exist
4034 // candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00004035 //
Douglas Gregora11693b2008-11-12 17:17:38 +00004036 // bool operator<(T, T);
4037 // bool operator>(T, T);
4038 // bool operator<=(T, T);
4039 // bool operator>=(T, T);
4040 // bool operator==(T, T);
4041 // bool operator!=(T, T);
4042 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4043 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4044 QualType ParamTypes[2] = { *Ptr, *Ptr };
4045 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
4046 }
Mike Stump11289f42009-09-09 15:08:12 +00004047 for (BuiltinCandidateTypeSet::iterator Enum
Douglas Gregora11693b2008-11-12 17:17:38 +00004048 = CandidateTypes.enumeration_begin();
4049 Enum != CandidateTypes.enumeration_end(); ++Enum) {
4050 QualType ParamTypes[2] = { *Enum, *Enum };
4051 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
4052 }
4053
4054 // Fall through.
4055 isComparison = true;
4056
Douglas Gregord08452f2008-11-19 15:42:04 +00004057 BinaryPlus:
4058 BinaryMinus:
Douglas Gregora11693b2008-11-12 17:17:38 +00004059 if (!isComparison) {
4060 // We didn't fall through, so we must have OO_Plus or OO_Minus.
4061
4062 // C++ [over.built]p13:
4063 //
4064 // For every cv-qualified or cv-unqualified object type T
4065 // there exist candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00004066 //
Douglas Gregora11693b2008-11-12 17:17:38 +00004067 // T* operator+(T*, ptrdiff_t);
4068 // T& operator[](T*, ptrdiff_t); [BELOW]
4069 // T* operator-(T*, ptrdiff_t);
4070 // T* operator+(ptrdiff_t, T*);
4071 // T& operator[](ptrdiff_t, T*); [BELOW]
4072 //
4073 // C++ [over.built]p14:
4074 //
4075 // For every T, where T is a pointer to object type, there
4076 // exist candidate operator functions of the form
4077 //
4078 // ptrdiff_t operator-(T, T);
Mike Stump11289f42009-09-09 15:08:12 +00004079 for (BuiltinCandidateTypeSet::iterator Ptr
Douglas Gregora11693b2008-11-12 17:17:38 +00004080 = CandidateTypes.pointer_begin();
4081 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4082 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
4083
4084 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
4085 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4086
4087 if (Op == OO_Plus) {
4088 // T* operator+(ptrdiff_t, T*);
4089 ParamTypes[0] = ParamTypes[1];
4090 ParamTypes[1] = *Ptr;
4091 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4092 } else {
4093 // ptrdiff_t operator-(T, T);
4094 ParamTypes[1] = *Ptr;
4095 AddBuiltinCandidate(Context.getPointerDiffType(), ParamTypes,
4096 Args, 2, CandidateSet);
4097 }
4098 }
4099 }
4100 // Fall through
4101
Douglas Gregora11693b2008-11-12 17:17:38 +00004102 case OO_Slash:
Douglas Gregord08452f2008-11-19 15:42:04 +00004103 BinaryStar:
Sebastian Redl1a99f442009-04-16 17:51:27 +00004104 Conditional:
Douglas Gregora11693b2008-11-12 17:17:38 +00004105 // C++ [over.built]p12:
4106 //
4107 // For every pair of promoted arithmetic types L and R, there
4108 // exist candidate operator functions of the form
4109 //
4110 // LR operator*(L, R);
4111 // LR operator/(L, R);
4112 // LR operator+(L, R);
4113 // LR operator-(L, R);
4114 // bool operator<(L, R);
4115 // bool operator>(L, R);
4116 // bool operator<=(L, R);
4117 // bool operator>=(L, R);
4118 // bool operator==(L, R);
4119 // bool operator!=(L, R);
4120 //
4121 // where LR is the result of the usual arithmetic conversions
4122 // between types L and R.
Sebastian Redl1a99f442009-04-16 17:51:27 +00004123 //
4124 // C++ [over.built]p24:
4125 //
4126 // For every pair of promoted arithmetic types L and R, there exist
4127 // candidate operator functions of the form
4128 //
4129 // LR operator?(bool, L, R);
4130 //
4131 // where LR is the result of the usual arithmetic conversions
4132 // between types L and R.
4133 // Our candidates ignore the first parameter.
Mike Stump11289f42009-09-09 15:08:12 +00004134 for (unsigned Left = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00004135 Left < LastPromotedArithmeticType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00004136 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00004137 Right < LastPromotedArithmeticType; ++Right) {
4138 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004139 QualType Result
4140 = isComparison
4141 ? Context.BoolTy
4142 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregora11693b2008-11-12 17:17:38 +00004143 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
4144 }
4145 }
4146 break;
4147
4148 case OO_Percent:
Douglas Gregord08452f2008-11-19 15:42:04 +00004149 BinaryAmp:
Douglas Gregora11693b2008-11-12 17:17:38 +00004150 case OO_Caret:
4151 case OO_Pipe:
4152 case OO_LessLess:
4153 case OO_GreaterGreater:
4154 // C++ [over.built]p17:
4155 //
4156 // For every pair of promoted integral types L and R, there
4157 // exist candidate operator functions of the form
4158 //
4159 // LR operator%(L, R);
4160 // LR operator&(L, R);
4161 // LR operator^(L, R);
4162 // LR operator|(L, R);
4163 // L operator<<(L, R);
4164 // L operator>>(L, R);
4165 //
4166 // where LR is the result of the usual arithmetic conversions
4167 // between types L and R.
Mike Stump11289f42009-09-09 15:08:12 +00004168 for (unsigned Left = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00004169 Left < LastPromotedIntegralType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00004170 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00004171 Right < LastPromotedIntegralType; ++Right) {
4172 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
4173 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
4174 ? LandR[0]
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004175 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregora11693b2008-11-12 17:17:38 +00004176 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
4177 }
4178 }
4179 break;
4180
4181 case OO_Equal:
4182 // C++ [over.built]p20:
4183 //
4184 // For every pair (T, VQ), where T is an enumeration or
Douglas Gregor84605ae2009-08-24 13:43:27 +00004185 // pointer to member type and VQ is either volatile or
Douglas Gregora11693b2008-11-12 17:17:38 +00004186 // empty, there exist candidate operator functions of the form
4187 //
4188 // VQ T& operator=(VQ T&, T);
Douglas Gregor84605ae2009-08-24 13:43:27 +00004189 for (BuiltinCandidateTypeSet::iterator
4190 Enum = CandidateTypes.enumeration_begin(),
4191 EnumEnd = CandidateTypes.enumeration_end();
4192 Enum != EnumEnd; ++Enum)
Mike Stump11289f42009-09-09 15:08:12 +00004193 AddBuiltinAssignmentOperatorCandidates(*this, *Enum, Args, 2,
Douglas Gregor84605ae2009-08-24 13:43:27 +00004194 CandidateSet);
4195 for (BuiltinCandidateTypeSet::iterator
4196 MemPtr = CandidateTypes.member_pointer_begin(),
4197 MemPtrEnd = CandidateTypes.member_pointer_end();
4198 MemPtr != MemPtrEnd; ++MemPtr)
Mike Stump11289f42009-09-09 15:08:12 +00004199 AddBuiltinAssignmentOperatorCandidates(*this, *MemPtr, Args, 2,
Douglas Gregor84605ae2009-08-24 13:43:27 +00004200 CandidateSet);
4201 // Fall through.
Douglas Gregora11693b2008-11-12 17:17:38 +00004202
4203 case OO_PlusEqual:
4204 case OO_MinusEqual:
4205 // C++ [over.built]p19:
4206 //
4207 // For every pair (T, VQ), where T is any type and VQ is either
4208 // volatile or empty, there exist candidate operator functions
4209 // of the form
4210 //
4211 // T*VQ& operator=(T*VQ&, T*);
4212 //
4213 // C++ [over.built]p21:
4214 //
4215 // For every pair (T, VQ), where T is a cv-qualified or
4216 // cv-unqualified object type and VQ is either volatile or
4217 // empty, there exist candidate operator functions of the form
4218 //
4219 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
4220 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
4221 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4222 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4223 QualType ParamTypes[2];
4224 ParamTypes[1] = (Op == OO_Equal)? *Ptr : Context.getPointerDiffType();
4225
4226 // non-volatile version
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004227 ParamTypes[0] = Context.getLValueReferenceType(*Ptr);
Douglas Gregorc5e61072009-01-13 00:52:54 +00004228 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4229 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00004230
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00004231 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
4232 VisibleTypeConversionsQuals.hasVolatile()) {
Douglas Gregord08452f2008-11-19 15:42:04 +00004233 // volatile version
John McCall8ccfcb52009-09-24 19:53:00 +00004234 ParamTypes[0]
4235 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregorc5e61072009-01-13 00:52:54 +00004236 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4237 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregord08452f2008-11-19 15:42:04 +00004238 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004239 }
4240 // Fall through.
4241
4242 case OO_StarEqual:
4243 case OO_SlashEqual:
4244 // C++ [over.built]p18:
4245 //
4246 // For every triple (L, VQ, R), where L is an arithmetic type,
4247 // VQ is either volatile or empty, and R is a promoted
4248 // arithmetic type, there exist candidate operator functions of
4249 // the form
4250 //
4251 // VQ L& operator=(VQ L&, R);
4252 // VQ L& operator*=(VQ L&, R);
4253 // VQ L& operator/=(VQ L&, R);
4254 // VQ L& operator+=(VQ L&, R);
4255 // VQ L& operator-=(VQ L&, R);
4256 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00004257 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00004258 Right < LastPromotedArithmeticType; ++Right) {
4259 QualType ParamTypes[2];
4260 ParamTypes[1] = ArithmeticTypes[Right];
4261
4262 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004263 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregorc5e61072009-01-13 00:52:54 +00004264 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4265 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00004266
4267 // Add this built-in operator as a candidate (VQ is 'volatile').
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00004268 if (VisibleTypeConversionsQuals.hasVolatile()) {
4269 ParamTypes[0] = Context.getVolatileType(ArithmeticTypes[Left]);
4270 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
4271 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4272 /*IsAssigmentOperator=*/Op == OO_Equal);
4273 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004274 }
4275 }
4276 break;
4277
4278 case OO_PercentEqual:
4279 case OO_LessLessEqual:
4280 case OO_GreaterGreaterEqual:
4281 case OO_AmpEqual:
4282 case OO_CaretEqual:
4283 case OO_PipeEqual:
4284 // C++ [over.built]p22:
4285 //
4286 // For every triple (L, VQ, R), where L is an integral type, VQ
4287 // is either volatile or empty, and R is a promoted integral
4288 // type, there exist candidate operator functions of the form
4289 //
4290 // VQ L& operator%=(VQ L&, R);
4291 // VQ L& operator<<=(VQ L&, R);
4292 // VQ L& operator>>=(VQ L&, R);
4293 // VQ L& operator&=(VQ L&, R);
4294 // VQ L& operator^=(VQ L&, R);
4295 // VQ L& operator|=(VQ L&, R);
4296 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00004297 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00004298 Right < LastPromotedIntegralType; ++Right) {
4299 QualType ParamTypes[2];
4300 ParamTypes[1] = ArithmeticTypes[Right];
4301
4302 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004303 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregora11693b2008-11-12 17:17:38 +00004304 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
Fariborz Jahaniana4a93342009-10-20 00:04:40 +00004305 if (VisibleTypeConversionsQuals.hasVolatile()) {
4306 // Add this built-in operator as a candidate (VQ is 'volatile').
4307 ParamTypes[0] = ArithmeticTypes[Left];
4308 ParamTypes[0] = Context.getVolatileType(ParamTypes[0]);
4309 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
4310 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
4311 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004312 }
4313 }
4314 break;
4315
Douglas Gregord08452f2008-11-19 15:42:04 +00004316 case OO_Exclaim: {
4317 // C++ [over.operator]p23:
4318 //
4319 // There also exist candidate operator functions of the form
4320 //
Mike Stump11289f42009-09-09 15:08:12 +00004321 // bool operator!(bool);
Douglas Gregord08452f2008-11-19 15:42:04 +00004322 // bool operator&&(bool, bool); [BELOW]
4323 // bool operator||(bool, bool); [BELOW]
4324 QualType ParamTy = Context.BoolTy;
Douglas Gregor5fb53972009-01-14 15:45:31 +00004325 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
4326 /*IsAssignmentOperator=*/false,
4327 /*NumContextualBoolArguments=*/1);
Douglas Gregord08452f2008-11-19 15:42:04 +00004328 break;
4329 }
4330
Douglas Gregora11693b2008-11-12 17:17:38 +00004331 case OO_AmpAmp:
4332 case OO_PipePipe: {
4333 // C++ [over.operator]p23:
4334 //
4335 // There also exist candidate operator functions of the form
4336 //
Douglas Gregord08452f2008-11-19 15:42:04 +00004337 // bool operator!(bool); [ABOVE]
Douglas Gregora11693b2008-11-12 17:17:38 +00004338 // bool operator&&(bool, bool);
4339 // bool operator||(bool, bool);
4340 QualType ParamTypes[2] = { Context.BoolTy, Context.BoolTy };
Douglas Gregor5fb53972009-01-14 15:45:31 +00004341 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
4342 /*IsAssignmentOperator=*/false,
4343 /*NumContextualBoolArguments=*/2);
Douglas Gregora11693b2008-11-12 17:17:38 +00004344 break;
4345 }
4346
4347 case OO_Subscript:
4348 // C++ [over.built]p13:
4349 //
4350 // For every cv-qualified or cv-unqualified object type T there
4351 // exist candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00004352 //
Douglas Gregora11693b2008-11-12 17:17:38 +00004353 // T* operator+(T*, ptrdiff_t); [ABOVE]
4354 // T& operator[](T*, ptrdiff_t);
4355 // T* operator-(T*, ptrdiff_t); [ABOVE]
4356 // T* operator+(ptrdiff_t, T*); [ABOVE]
4357 // T& operator[](ptrdiff_t, T*);
4358 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4359 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4360 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004361 QualType PointeeType = (*Ptr)->getAs<PointerType>()->getPointeeType();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004362 QualType ResultTy = Context.getLValueReferenceType(PointeeType);
Douglas Gregora11693b2008-11-12 17:17:38 +00004363
4364 // T& operator[](T*, ptrdiff_t)
4365 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
4366
4367 // T& operator[](ptrdiff_t, T*);
4368 ParamTypes[0] = ParamTypes[1];
4369 ParamTypes[1] = *Ptr;
4370 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
4371 }
4372 break;
4373
4374 case OO_ArrowStar:
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00004375 // C++ [over.built]p11:
4376 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
4377 // C1 is the same type as C2 or is a derived class of C2, T is an object
4378 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
4379 // there exist candidate operator functions of the form
4380 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
4381 // where CV12 is the union of CV1 and CV2.
4382 {
4383 for (BuiltinCandidateTypeSet::iterator Ptr =
4384 CandidateTypes.pointer_begin();
4385 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4386 QualType C1Ty = (*Ptr);
4387 QualType C1;
Fariborz Jahanian4dc12462009-10-09 16:34:40 +00004388 QualifierCollector Q1;
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00004389 if (const PointerType *PointerTy = C1Ty->getAs<PointerType>()) {
Fariborz Jahanian4dc12462009-10-09 16:34:40 +00004390 C1 = QualType(Q1.strip(PointerTy->getPointeeType()), 0);
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00004391 if (!isa<RecordType>(C1))
4392 continue;
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004393 // heuristic to reduce number of builtin candidates in the set.
4394 // Add volatile/restrict version only if there are conversions to a
4395 // volatile/restrict type.
4396 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
4397 continue;
4398 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
4399 continue;
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00004400 }
4401 for (BuiltinCandidateTypeSet::iterator
4402 MemPtr = CandidateTypes.member_pointer_begin(),
4403 MemPtrEnd = CandidateTypes.member_pointer_end();
4404 MemPtr != MemPtrEnd; ++MemPtr) {
4405 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
4406 QualType C2 = QualType(mptr->getClass(), 0);
Fariborz Jahanian12df37c2009-10-07 16:56:50 +00004407 C2 = C2.getUnqualifiedType();
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00004408 if (C1 != C2 && !IsDerivedFrom(C1, C2))
4409 break;
4410 QualType ParamTypes[2] = { *Ptr, *MemPtr };
4411 // build CV12 T&
4412 QualType T = mptr->getPointeeType();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004413 if (!VisibleTypeConversionsQuals.hasVolatile() &&
4414 T.isVolatileQualified())
4415 continue;
4416 if (!VisibleTypeConversionsQuals.hasRestrict() &&
4417 T.isRestrictQualified())
4418 continue;
Fariborz Jahanian4dc12462009-10-09 16:34:40 +00004419 T = Q1.apply(T);
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00004420 QualType ResultTy = Context.getLValueReferenceType(T);
4421 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
4422 }
4423 }
4424 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004425 break;
Sebastian Redl1a99f442009-04-16 17:51:27 +00004426
4427 case OO_Conditional:
4428 // Note that we don't consider the first argument, since it has been
4429 // contextually converted to bool long ago. The candidates below are
4430 // therefore added as binary.
4431 //
4432 // C++ [over.built]p24:
4433 // For every type T, where T is a pointer or pointer-to-member type,
4434 // there exist candidate operator functions of the form
4435 //
4436 // T operator?(bool, T, T);
4437 //
Sebastian Redl1a99f442009-04-16 17:51:27 +00004438 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin(),
4439 E = CandidateTypes.pointer_end(); Ptr != E; ++Ptr) {
4440 QualType ParamTypes[2] = { *Ptr, *Ptr };
4441 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4442 }
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004443 for (BuiltinCandidateTypeSet::iterator Ptr =
4444 CandidateTypes.member_pointer_begin(),
4445 E = CandidateTypes.member_pointer_end(); Ptr != E; ++Ptr) {
4446 QualType ParamTypes[2] = { *Ptr, *Ptr };
4447 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4448 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00004449 goto Conditional;
Douglas Gregora11693b2008-11-12 17:17:38 +00004450 }
4451}
4452
Douglas Gregore254f902009-02-04 00:32:51 +00004453/// \brief Add function candidates found via argument-dependent lookup
4454/// to the set of overloading candidates.
4455///
4456/// This routine performs argument-dependent name lookup based on the
4457/// given function name (which may also be an operator name) and adds
4458/// all of the overload candidates found by ADL to the overload
4459/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump11289f42009-09-09 15:08:12 +00004460void
Douglas Gregore254f902009-02-04 00:32:51 +00004461Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
John McCall4c4c1df2010-01-26 03:27:55 +00004462 bool Operator,
Douglas Gregore254f902009-02-04 00:32:51 +00004463 Expr **Args, unsigned NumArgs,
John McCall6b51f282009-11-23 01:53:49 +00004464 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00004465 OverloadCandidateSet& CandidateSet,
4466 bool PartialOverloading) {
John McCall8fe68082010-01-26 07:16:45 +00004467 ADLResult Fns;
Douglas Gregore254f902009-02-04 00:32:51 +00004468
John McCall91f61fc2010-01-26 06:04:06 +00004469 // FIXME: This approach for uniquing ADL results (and removing
4470 // redundant candidates from the set) relies on pointer-equality,
4471 // which means we need to key off the canonical decl. However,
4472 // always going back to the canonical decl might not get us the
4473 // right set of default arguments. What default arguments are
4474 // we supposed to consider on ADL candidates, anyway?
4475
Douglas Gregorcabea402009-09-22 15:41:20 +00004476 // FIXME: Pass in the explicit template arguments?
John McCall8fe68082010-01-26 07:16:45 +00004477 ArgumentDependentLookup(Name, Operator, Args, NumArgs, Fns);
Douglas Gregore254f902009-02-04 00:32:51 +00004478
Douglas Gregord2b7ef62009-03-13 00:33:25 +00004479 // Erase all of the candidates we already knew about.
Douglas Gregord2b7ef62009-03-13 00:33:25 +00004480 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
4481 CandEnd = CandidateSet.end();
4482 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00004483 if (Cand->Function) {
John McCall8fe68082010-01-26 07:16:45 +00004484 Fns.erase(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00004485 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall8fe68082010-01-26 07:16:45 +00004486 Fns.erase(FunTmpl);
Douglas Gregor15448f82009-06-27 21:05:07 +00004487 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00004488
4489 // For each of the ADL candidates we found, add it to the overload
4490 // set.
John McCall8fe68082010-01-26 07:16:45 +00004491 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00004492 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall4c4c1df2010-01-26 03:27:55 +00004493 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCall6b51f282009-11-23 01:53:49 +00004494 if (ExplicitTemplateArgs)
Douglas Gregorcabea402009-09-22 15:41:20 +00004495 continue;
4496
John McCalla0296f72010-03-19 07:35:19 +00004497 AddOverloadCandidate(FD, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorb05275a2010-04-16 17:41:49 +00004498 false, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00004499 } else
John McCall4c4c1df2010-01-26 03:27:55 +00004500 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCalla0296f72010-03-19 07:35:19 +00004501 FoundDecl, ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00004502 Args, NumArgs, CandidateSet);
Douglas Gregor15448f82009-06-27 21:05:07 +00004503 }
Douglas Gregore254f902009-02-04 00:32:51 +00004504}
4505
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004506/// isBetterOverloadCandidate - Determines whether the first overload
4507/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump11289f42009-09-09 15:08:12 +00004508bool
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004509Sema::isBetterOverloadCandidate(const OverloadCandidate& Cand1,
John McCallbc077cf2010-02-08 23:07:23 +00004510 const OverloadCandidate& Cand2,
4511 SourceLocation Loc) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004512 // Define viable functions to be better candidates than non-viable
4513 // functions.
4514 if (!Cand2.Viable)
4515 return Cand1.Viable;
4516 else if (!Cand1.Viable)
4517 return false;
4518
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004519 // C++ [over.match.best]p1:
4520 //
4521 // -- if F is a static member function, ICS1(F) is defined such
4522 // that ICS1(F) is neither better nor worse than ICS1(G) for
4523 // any function G, and, symmetrically, ICS1(G) is neither
4524 // better nor worse than ICS1(F).
4525 unsigned StartArg = 0;
4526 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
4527 StartArg = 1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004528
Douglas Gregord3cb3562009-07-07 23:38:56 +00004529 // C++ [over.match.best]p1:
Mike Stump11289f42009-09-09 15:08:12 +00004530 // A viable function F1 is defined to be a better function than another
4531 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregord3cb3562009-07-07 23:38:56 +00004532 // conversion sequence than ICSi(F2), and then...
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004533 unsigned NumArgs = Cand1.Conversions.size();
4534 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
4535 bool HasBetterConversion = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004536 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004537 switch (CompareImplicitConversionSequences(Cand1.Conversions[ArgIdx],
4538 Cand2.Conversions[ArgIdx])) {
4539 case ImplicitConversionSequence::Better:
4540 // Cand1 has a better conversion sequence.
4541 HasBetterConversion = true;
4542 break;
4543
4544 case ImplicitConversionSequence::Worse:
4545 // Cand1 can't be better than Cand2.
4546 return false;
4547
4548 case ImplicitConversionSequence::Indistinguishable:
4549 // Do nothing.
4550 break;
4551 }
4552 }
4553
Mike Stump11289f42009-09-09 15:08:12 +00004554 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregord3cb3562009-07-07 23:38:56 +00004555 // ICSj(F2), or, if not that,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004556 if (HasBetterConversion)
4557 return true;
4558
Mike Stump11289f42009-09-09 15:08:12 +00004559 // - F1 is a non-template function and F2 is a function template
Douglas Gregord3cb3562009-07-07 23:38:56 +00004560 // specialization, or, if not that,
4561 if (Cand1.Function && !Cand1.Function->getPrimaryTemplate() &&
4562 Cand2.Function && Cand2.Function->getPrimaryTemplate())
4563 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004564
4565 // -- F1 and F2 are function template specializations, and the function
4566 // template for F1 is more specialized than the template for F2
4567 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregord3cb3562009-07-07 23:38:56 +00004568 // if not that,
Douglas Gregor55137cb2009-08-02 23:46:29 +00004569 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
4570 Cand2.Function && Cand2.Function->getPrimaryTemplate())
Douglas Gregor05155d82009-08-21 23:19:43 +00004571 if (FunctionTemplateDecl *BetterTemplate
4572 = getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
4573 Cand2.Function->getPrimaryTemplate(),
John McCallbc077cf2010-02-08 23:07:23 +00004574 Loc,
Douglas Gregor6010da02009-09-14 23:02:14 +00004575 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
4576 : TPOC_Call))
Douglas Gregor05155d82009-08-21 23:19:43 +00004577 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004578
Douglas Gregora1f013e2008-11-07 22:36:19 +00004579 // -- the context is an initialization by user-defined conversion
4580 // (see 8.5, 13.3.1.5) and the standard conversion sequence
4581 // from the return type of F1 to the destination type (i.e.,
4582 // the type of the entity being initialized) is a better
4583 // conversion sequence than the standard conversion sequence
4584 // from the return type of F2 to the destination type.
Mike Stump11289f42009-09-09 15:08:12 +00004585 if (Cand1.Function && Cand2.Function &&
4586 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00004587 isa<CXXConversionDecl>(Cand2.Function)) {
4588 switch (CompareStandardConversionSequences(Cand1.FinalConversion,
4589 Cand2.FinalConversion)) {
4590 case ImplicitConversionSequence::Better:
4591 // Cand1 has a better conversion sequence.
4592 return true;
4593
4594 case ImplicitConversionSequence::Worse:
4595 // Cand1 can't be better than Cand2.
4596 return false;
4597
4598 case ImplicitConversionSequence::Indistinguishable:
4599 // Do nothing
4600 break;
4601 }
4602 }
4603
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004604 return false;
4605}
4606
Mike Stump11289f42009-09-09 15:08:12 +00004607/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004608/// within an overload candidate set.
4609///
4610/// \param CandidateSet the set of candidate functions.
4611///
4612/// \param Loc the location of the function name (or operator symbol) for
4613/// which overload resolution occurs.
4614///
Mike Stump11289f42009-09-09 15:08:12 +00004615/// \param Best f overload resolution was successful or found a deleted
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004616/// function, Best points to the candidate function found.
4617///
4618/// \returns The result of overload resolution.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004619OverloadingResult Sema::BestViableFunction(OverloadCandidateSet& CandidateSet,
4620 SourceLocation Loc,
4621 OverloadCandidateSet::iterator& Best) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004622 // Find the best viable function.
4623 Best = CandidateSet.end();
4624 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4625 Cand != CandidateSet.end(); ++Cand) {
4626 if (Cand->Viable) {
John McCallbc077cf2010-02-08 23:07:23 +00004627 if (Best == CandidateSet.end() ||
4628 isBetterOverloadCandidate(*Cand, *Best, Loc))
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004629 Best = Cand;
4630 }
4631 }
4632
4633 // If we didn't find any viable functions, abort.
4634 if (Best == CandidateSet.end())
4635 return OR_No_Viable_Function;
4636
4637 // Make sure that this function is better than every other viable
4638 // function. If not, we have an ambiguity.
4639 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4640 Cand != CandidateSet.end(); ++Cand) {
Mike Stump11289f42009-09-09 15:08:12 +00004641 if (Cand->Viable &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004642 Cand != Best &&
John McCallbc077cf2010-02-08 23:07:23 +00004643 !isBetterOverloadCandidate(*Best, *Cand, Loc)) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00004644 Best = CandidateSet.end();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004645 return OR_Ambiguous;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004646 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004647 }
Mike Stump11289f42009-09-09 15:08:12 +00004648
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004649 // Best is the best viable function.
Douglas Gregor171c45a2009-02-18 21:56:37 +00004650 if (Best->Function &&
Mike Stump11289f42009-09-09 15:08:12 +00004651 (Best->Function->isDeleted() ||
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00004652 Best->Function->getAttr<UnavailableAttr>()))
Douglas Gregor171c45a2009-02-18 21:56:37 +00004653 return OR_Deleted;
4654
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004655 // C++ [basic.def.odr]p2:
4656 // An overloaded function is used if it is selected by overload resolution
Mike Stump11289f42009-09-09 15:08:12 +00004657 // when referred to from a potentially-evaluated expression. [Note: this
4658 // covers calls to named functions (5.2.2), operator overloading
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004659 // (clause 13), user-defined conversions (12.3.2), allocation function for
4660 // placement new (5.3.4), as well as non-default initialization (8.5).
4661 if (Best->Function)
4662 MarkDeclarationReferenced(Loc, Best->Function);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004663 return OR_Success;
4664}
4665
John McCall53262c92010-01-12 02:15:36 +00004666namespace {
4667
4668enum OverloadCandidateKind {
4669 oc_function,
4670 oc_method,
4671 oc_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00004672 oc_function_template,
4673 oc_method_template,
4674 oc_constructor_template,
John McCall53262c92010-01-12 02:15:36 +00004675 oc_implicit_default_constructor,
4676 oc_implicit_copy_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00004677 oc_implicit_copy_assignment
John McCall53262c92010-01-12 02:15:36 +00004678};
4679
John McCalle1ac8d12010-01-13 00:25:19 +00004680OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
4681 FunctionDecl *Fn,
4682 std::string &Description) {
4683 bool isTemplate = false;
4684
4685 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
4686 isTemplate = true;
4687 Description = S.getTemplateArgumentBindingsText(
4688 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
4689 }
John McCallfd0b2f82010-01-06 09:43:14 +00004690
4691 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall53262c92010-01-12 02:15:36 +00004692 if (!Ctor->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00004693 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00004694
John McCall53262c92010-01-12 02:15:36 +00004695 return Ctor->isCopyConstructor() ? oc_implicit_copy_constructor
4696 : oc_implicit_default_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00004697 }
4698
4699 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
4700 // This actually gets spelled 'candidate function' for now, but
4701 // it doesn't hurt to split it out.
John McCall53262c92010-01-12 02:15:36 +00004702 if (!Meth->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00004703 return isTemplate ? oc_method_template : oc_method;
John McCallfd0b2f82010-01-06 09:43:14 +00004704
4705 assert(Meth->isCopyAssignment()
4706 && "implicit method is not copy assignment operator?");
John McCall53262c92010-01-12 02:15:36 +00004707 return oc_implicit_copy_assignment;
4708 }
4709
John McCalle1ac8d12010-01-13 00:25:19 +00004710 return isTemplate ? oc_function_template : oc_function;
John McCall53262c92010-01-12 02:15:36 +00004711}
4712
4713} // end anonymous namespace
4714
4715// Notes the location of an overload candidate.
4716void Sema::NoteOverloadCandidate(FunctionDecl *Fn) {
John McCalle1ac8d12010-01-13 00:25:19 +00004717 std::string FnDesc;
4718 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
4719 Diag(Fn->getLocation(), diag::note_ovl_candidate)
4720 << (unsigned) K << FnDesc;
John McCallfd0b2f82010-01-06 09:43:14 +00004721}
4722
John McCall0d1da222010-01-12 00:44:57 +00004723/// Diagnoses an ambiguous conversion. The partial diagnostic is the
4724/// "lead" diagnostic; it will be given two arguments, the source and
4725/// target types of the conversion.
4726void Sema::DiagnoseAmbiguousConversion(const ImplicitConversionSequence &ICS,
4727 SourceLocation CaretLoc,
4728 const PartialDiagnostic &PDiag) {
4729 Diag(CaretLoc, PDiag)
4730 << ICS.Ambiguous.getFromType() << ICS.Ambiguous.getToType();
4731 for (AmbiguousConversionSequence::const_iterator
4732 I = ICS.Ambiguous.begin(), E = ICS.Ambiguous.end(); I != E; ++I) {
4733 NoteOverloadCandidate(*I);
4734 }
John McCall12f97bc2010-01-08 04:41:39 +00004735}
4736
John McCall0d1da222010-01-12 00:44:57 +00004737namespace {
4738
John McCall6a61b522010-01-13 09:16:55 +00004739void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
4740 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
4741 assert(Conv.isBad());
John McCalle1ac8d12010-01-13 00:25:19 +00004742 assert(Cand->Function && "for now, candidate must be a function");
4743 FunctionDecl *Fn = Cand->Function;
4744
4745 // There's a conversion slot for the object argument if this is a
4746 // non-constructor method. Note that 'I' corresponds the
4747 // conversion-slot index.
John McCall6a61b522010-01-13 09:16:55 +00004748 bool isObjectArgument = false;
John McCalle1ac8d12010-01-13 00:25:19 +00004749 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCall6a61b522010-01-13 09:16:55 +00004750 if (I == 0)
4751 isObjectArgument = true;
4752 else
4753 I--;
John McCalle1ac8d12010-01-13 00:25:19 +00004754 }
4755
John McCalle1ac8d12010-01-13 00:25:19 +00004756 std::string FnDesc;
4757 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
4758
John McCall6a61b522010-01-13 09:16:55 +00004759 Expr *FromExpr = Conv.Bad.FromExpr;
4760 QualType FromTy = Conv.Bad.getFromType();
4761 QualType ToTy = Conv.Bad.getToType();
John McCalle1ac8d12010-01-13 00:25:19 +00004762
John McCallfb7ad0f2010-02-02 02:42:52 +00004763 if (FromTy == S.Context.OverloadTy) {
John McCall65eb8792010-02-25 01:37:24 +00004764 assert(FromExpr && "overload set argument came from implicit argument?");
John McCallfb7ad0f2010-02-02 02:42:52 +00004765 Expr *E = FromExpr->IgnoreParens();
4766 if (isa<UnaryOperator>(E))
4767 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall1acbbb52010-02-02 06:20:04 +00004768 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCallfb7ad0f2010-02-02 02:42:52 +00004769
4770 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
4771 << (unsigned) FnKind << FnDesc
4772 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
4773 << ToTy << Name << I+1;
4774 return;
4775 }
4776
John McCall6d174642010-01-23 08:10:49 +00004777 // Do some hand-waving analysis to see if the non-viability is due
4778 // to a qualifier mismatch.
John McCall47000992010-01-14 03:28:57 +00004779 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
4780 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
4781 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
4782 CToTy = RT->getPointeeType();
4783 else {
4784 // TODO: detect and diagnose the full richness of const mismatches.
4785 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
4786 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
4787 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
4788 }
4789
4790 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
4791 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
4792 // It is dumb that we have to do this here.
4793 while (isa<ArrayType>(CFromTy))
4794 CFromTy = CFromTy->getAs<ArrayType>()->getElementType();
4795 while (isa<ArrayType>(CToTy))
4796 CToTy = CFromTy->getAs<ArrayType>()->getElementType();
4797
4798 Qualifiers FromQs = CFromTy.getQualifiers();
4799 Qualifiers ToQs = CToTy.getQualifiers();
4800
4801 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
4802 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
4803 << (unsigned) FnKind << FnDesc
4804 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
4805 << FromTy
4806 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
4807 << (unsigned) isObjectArgument << I+1;
4808 return;
4809 }
4810
4811 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
4812 assert(CVR && "unexpected qualifiers mismatch");
4813
4814 if (isObjectArgument) {
4815 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
4816 << (unsigned) FnKind << FnDesc
4817 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
4818 << FromTy << (CVR - 1);
4819 } else {
4820 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
4821 << (unsigned) FnKind << FnDesc
4822 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
4823 << FromTy << (CVR - 1) << I+1;
4824 }
4825 return;
4826 }
4827
John McCall6d174642010-01-23 08:10:49 +00004828 // Diagnose references or pointers to incomplete types differently,
4829 // since it's far from impossible that the incompleteness triggered
4830 // the failure.
4831 QualType TempFromTy = FromTy.getNonReferenceType();
4832 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
4833 TempFromTy = PTy->getPointeeType();
4834 if (TempFromTy->isIncompleteType()) {
4835 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
4836 << (unsigned) FnKind << FnDesc
4837 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
4838 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
4839 return;
4840 }
4841
John McCall47000992010-01-14 03:28:57 +00004842 // TODO: specialize more based on the kind of mismatch
John McCalle1ac8d12010-01-13 00:25:19 +00004843 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv)
4844 << (unsigned) FnKind << FnDesc
John McCall6a61b522010-01-13 09:16:55 +00004845 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
John McCalla1709fd2010-01-14 00:56:20 +00004846 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
John McCall6a61b522010-01-13 09:16:55 +00004847}
4848
4849void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
4850 unsigned NumFormalArgs) {
4851 // TODO: treat calls to a missing default constructor as a special case
4852
4853 FunctionDecl *Fn = Cand->Function;
4854 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
4855
4856 unsigned MinParams = Fn->getMinRequiredArguments();
4857
4858 // at least / at most / exactly
4859 unsigned mode, modeCount;
4860 if (NumFormalArgs < MinParams) {
4861 assert(Cand->FailureKind == ovl_fail_too_few_arguments);
4862 if (MinParams != FnTy->getNumArgs() || FnTy->isVariadic())
4863 mode = 0; // "at least"
4864 else
4865 mode = 2; // "exactly"
4866 modeCount = MinParams;
4867 } else {
4868 assert(Cand->FailureKind == ovl_fail_too_many_arguments);
4869 if (MinParams != FnTy->getNumArgs())
4870 mode = 1; // "at most"
4871 else
4872 mode = 2; // "exactly"
4873 modeCount = FnTy->getNumArgs();
4874 }
4875
4876 std::string Description;
4877 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
4878
4879 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
4880 << (unsigned) FnKind << Description << mode << modeCount << NumFormalArgs;
John McCalle1ac8d12010-01-13 00:25:19 +00004881}
4882
John McCall8b9ed552010-02-01 18:53:26 +00004883/// Diagnose a failed template-argument deduction.
4884void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
4885 Expr **Args, unsigned NumArgs) {
4886 FunctionDecl *Fn = Cand->Function; // pattern
4887
4888 TemplateParameter Param = TemplateParameter::getFromOpaqueValue(
4889 Cand->DeductionFailure.TemplateParameter);
4890
4891 switch (Cand->DeductionFailure.Result) {
4892 case Sema::TDK_Success:
4893 llvm_unreachable("TDK_success while diagnosing bad deduction");
4894
4895 case Sema::TDK_Incomplete: {
4896 NamedDecl *ParamD;
4897 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
4898 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
4899 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
4900 assert(ParamD && "no parameter found for incomplete deduction result");
4901 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction)
4902 << ParamD->getDeclName();
4903 return;
4904 }
4905
4906 // TODO: diagnose these individually, then kill off
4907 // note_ovl_candidate_bad_deduction, which is uselessly vague.
4908 case Sema::TDK_InstantiationDepth:
4909 case Sema::TDK_Inconsistent:
4910 case Sema::TDK_InconsistentQuals:
4911 case Sema::TDK_SubstitutionFailure:
4912 case Sema::TDK_NonDeducedMismatch:
4913 case Sema::TDK_TooManyArguments:
4914 case Sema::TDK_TooFewArguments:
4915 case Sema::TDK_InvalidExplicitArguments:
4916 case Sema::TDK_FailedOverloadResolution:
4917 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction);
4918 return;
4919 }
4920}
4921
4922/// Generates a 'note' diagnostic for an overload candidate. We've
4923/// already generated a primary error at the call site.
4924///
4925/// It really does need to be a single diagnostic with its caret
4926/// pointed at the candidate declaration. Yes, this creates some
4927/// major challenges of technical writing. Yes, this makes pointing
4928/// out problems with specific arguments quite awkward. It's still
4929/// better than generating twenty screens of text for every failed
4930/// overload.
4931///
4932/// It would be great to be able to express per-candidate problems
4933/// more richly for those diagnostic clients that cared, but we'd
4934/// still have to be just as careful with the default diagnostics.
John McCalle1ac8d12010-01-13 00:25:19 +00004935void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
4936 Expr **Args, unsigned NumArgs) {
John McCall53262c92010-01-12 02:15:36 +00004937 FunctionDecl *Fn = Cand->Function;
4938
John McCall12f97bc2010-01-08 04:41:39 +00004939 // Note deleted candidates, but only if they're viable.
John McCall53262c92010-01-12 02:15:36 +00004940 if (Cand->Viable && (Fn->isDeleted() || Fn->hasAttr<UnavailableAttr>())) {
John McCalle1ac8d12010-01-13 00:25:19 +00004941 std::string FnDesc;
4942 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall53262c92010-01-12 02:15:36 +00004943
4944 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
John McCalle1ac8d12010-01-13 00:25:19 +00004945 << FnKind << FnDesc << Fn->isDeleted();
John McCalld3224162010-01-08 00:58:21 +00004946 return;
John McCall12f97bc2010-01-08 04:41:39 +00004947 }
4948
John McCalle1ac8d12010-01-13 00:25:19 +00004949 // We don't really have anything else to say about viable candidates.
4950 if (Cand->Viable) {
4951 S.NoteOverloadCandidate(Fn);
4952 return;
4953 }
John McCall0d1da222010-01-12 00:44:57 +00004954
John McCall6a61b522010-01-13 09:16:55 +00004955 switch (Cand->FailureKind) {
4956 case ovl_fail_too_many_arguments:
4957 case ovl_fail_too_few_arguments:
4958 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCalle1ac8d12010-01-13 00:25:19 +00004959
John McCall6a61b522010-01-13 09:16:55 +00004960 case ovl_fail_bad_deduction:
John McCall8b9ed552010-02-01 18:53:26 +00004961 return DiagnoseBadDeduction(S, Cand, Args, NumArgs);
4962
John McCallfe796dd2010-01-23 05:17:32 +00004963 case ovl_fail_trivial_conversion:
4964 case ovl_fail_bad_final_conversion:
Douglas Gregor2c326bc2010-04-12 23:42:09 +00004965 case ovl_fail_final_conversion_not_exact:
John McCall6a61b522010-01-13 09:16:55 +00004966 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00004967
John McCall65eb8792010-02-25 01:37:24 +00004968 case ovl_fail_bad_conversion: {
4969 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
4970 for (unsigned N = Cand->Conversions.size(); I != N; ++I)
John McCall6a61b522010-01-13 09:16:55 +00004971 if (Cand->Conversions[I].isBad())
4972 return DiagnoseBadConversion(S, Cand, I);
4973
4974 // FIXME: this currently happens when we're called from SemaInit
4975 // when user-conversion overload fails. Figure out how to handle
4976 // those conditions and diagnose them well.
4977 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00004978 }
John McCall65eb8792010-02-25 01:37:24 +00004979 }
John McCalld3224162010-01-08 00:58:21 +00004980}
4981
4982void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
4983 // Desugar the type of the surrogate down to a function type,
4984 // retaining as many typedefs as possible while still showing
4985 // the function type (and, therefore, its parameter types).
4986 QualType FnType = Cand->Surrogate->getConversionType();
4987 bool isLValueReference = false;
4988 bool isRValueReference = false;
4989 bool isPointer = false;
4990 if (const LValueReferenceType *FnTypeRef =
4991 FnType->getAs<LValueReferenceType>()) {
4992 FnType = FnTypeRef->getPointeeType();
4993 isLValueReference = true;
4994 } else if (const RValueReferenceType *FnTypeRef =
4995 FnType->getAs<RValueReferenceType>()) {
4996 FnType = FnTypeRef->getPointeeType();
4997 isRValueReference = true;
4998 }
4999 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
5000 FnType = FnTypePtr->getPointeeType();
5001 isPointer = true;
5002 }
5003 // Desugar down to a function type.
5004 FnType = QualType(FnType->getAs<FunctionType>(), 0);
5005 // Reconstruct the pointer/reference as appropriate.
5006 if (isPointer) FnType = S.Context.getPointerType(FnType);
5007 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
5008 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
5009
5010 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
5011 << FnType;
5012}
5013
5014void NoteBuiltinOperatorCandidate(Sema &S,
5015 const char *Opc,
5016 SourceLocation OpLoc,
5017 OverloadCandidate *Cand) {
5018 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
5019 std::string TypeStr("operator");
5020 TypeStr += Opc;
5021 TypeStr += "(";
5022 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
5023 if (Cand->Conversions.size() == 1) {
5024 TypeStr += ")";
5025 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
5026 } else {
5027 TypeStr += ", ";
5028 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
5029 TypeStr += ")";
5030 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
5031 }
5032}
5033
5034void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
5035 OverloadCandidate *Cand) {
5036 unsigned NoOperands = Cand->Conversions.size();
5037 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
5038 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall0d1da222010-01-12 00:44:57 +00005039 if (ICS.isBad()) break; // all meaningless after first invalid
5040 if (!ICS.isAmbiguous()) continue;
5041
5042 S.DiagnoseAmbiguousConversion(ICS, OpLoc,
Douglas Gregor89336232010-03-29 23:34:08 +00005043 S.PDiag(diag::note_ambiguous_type_conversion));
John McCalld3224162010-01-08 00:58:21 +00005044 }
5045}
5046
John McCall3712d9e2010-01-15 23:32:50 +00005047SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
5048 if (Cand->Function)
5049 return Cand->Function->getLocation();
John McCall982adb52010-01-16 03:50:16 +00005050 if (Cand->IsSurrogate)
John McCall3712d9e2010-01-15 23:32:50 +00005051 return Cand->Surrogate->getLocation();
5052 return SourceLocation();
5053}
5054
John McCallad2587a2010-01-12 00:48:53 +00005055struct CompareOverloadCandidatesForDisplay {
5056 Sema &S;
5057 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
John McCall12f97bc2010-01-08 04:41:39 +00005058
5059 bool operator()(const OverloadCandidate *L,
5060 const OverloadCandidate *R) {
John McCall982adb52010-01-16 03:50:16 +00005061 // Fast-path this check.
5062 if (L == R) return false;
5063
John McCall12f97bc2010-01-08 04:41:39 +00005064 // Order first by viability.
John McCallad2587a2010-01-12 00:48:53 +00005065 if (L->Viable) {
5066 if (!R->Viable) return true;
5067
5068 // TODO: introduce a tri-valued comparison for overload
5069 // candidates. Would be more worthwhile if we had a sort
5070 // that could exploit it.
John McCallbc077cf2010-02-08 23:07:23 +00005071 if (S.isBetterOverloadCandidate(*L, *R, SourceLocation())) return true;
5072 if (S.isBetterOverloadCandidate(*R, *L, SourceLocation())) return false;
John McCallad2587a2010-01-12 00:48:53 +00005073 } else if (R->Viable)
5074 return false;
John McCall12f97bc2010-01-08 04:41:39 +00005075
John McCall3712d9e2010-01-15 23:32:50 +00005076 assert(L->Viable == R->Viable);
John McCall12f97bc2010-01-08 04:41:39 +00005077
John McCall3712d9e2010-01-15 23:32:50 +00005078 // Criteria by which we can sort non-viable candidates:
5079 if (!L->Viable) {
5080 // 1. Arity mismatches come after other candidates.
5081 if (L->FailureKind == ovl_fail_too_many_arguments ||
5082 L->FailureKind == ovl_fail_too_few_arguments)
5083 return false;
5084 if (R->FailureKind == ovl_fail_too_many_arguments ||
5085 R->FailureKind == ovl_fail_too_few_arguments)
5086 return true;
John McCall12f97bc2010-01-08 04:41:39 +00005087
John McCallfe796dd2010-01-23 05:17:32 +00005088 // 2. Bad conversions come first and are ordered by the number
5089 // of bad conversions and quality of good conversions.
5090 if (L->FailureKind == ovl_fail_bad_conversion) {
5091 if (R->FailureKind != ovl_fail_bad_conversion)
5092 return true;
5093
5094 // If there's any ordering between the defined conversions...
5095 // FIXME: this might not be transitive.
5096 assert(L->Conversions.size() == R->Conversions.size());
5097
5098 int leftBetter = 0;
John McCall21b57fa2010-02-25 10:46:05 +00005099 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
5100 for (unsigned E = L->Conversions.size(); I != E; ++I) {
John McCallfe796dd2010-01-23 05:17:32 +00005101 switch (S.CompareImplicitConversionSequences(L->Conversions[I],
5102 R->Conversions[I])) {
5103 case ImplicitConversionSequence::Better:
5104 leftBetter++;
5105 break;
5106
5107 case ImplicitConversionSequence::Worse:
5108 leftBetter--;
5109 break;
5110
5111 case ImplicitConversionSequence::Indistinguishable:
5112 break;
5113 }
5114 }
5115 if (leftBetter > 0) return true;
5116 if (leftBetter < 0) return false;
5117
5118 } else if (R->FailureKind == ovl_fail_bad_conversion)
5119 return false;
5120
John McCall3712d9e2010-01-15 23:32:50 +00005121 // TODO: others?
5122 }
5123
5124 // Sort everything else by location.
5125 SourceLocation LLoc = GetLocationForCandidate(L);
5126 SourceLocation RLoc = GetLocationForCandidate(R);
5127
5128 // Put candidates without locations (e.g. builtins) at the end.
5129 if (LLoc.isInvalid()) return false;
5130 if (RLoc.isInvalid()) return true;
5131
5132 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall12f97bc2010-01-08 04:41:39 +00005133 }
5134};
5135
John McCallfe796dd2010-01-23 05:17:32 +00005136/// CompleteNonViableCandidate - Normally, overload resolution only
5137/// computes up to the first
5138void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
5139 Expr **Args, unsigned NumArgs) {
5140 assert(!Cand->Viable);
5141
5142 // Don't do anything on failures other than bad conversion.
5143 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
5144
5145 // Skip forward to the first bad conversion.
John McCall65eb8792010-02-25 01:37:24 +00005146 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
John McCallfe796dd2010-01-23 05:17:32 +00005147 unsigned ConvCount = Cand->Conversions.size();
5148 while (true) {
5149 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
5150 ConvIdx++;
5151 if (Cand->Conversions[ConvIdx - 1].isBad())
5152 break;
5153 }
5154
5155 if (ConvIdx == ConvCount)
5156 return;
5157
John McCall65eb8792010-02-25 01:37:24 +00005158 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
5159 "remaining conversion is initialized?");
5160
Douglas Gregoradc7a702010-04-16 17:45:54 +00005161 // FIXME: this should probably be preserved from the overload
John McCallfe796dd2010-01-23 05:17:32 +00005162 // operation somehow.
5163 bool SuppressUserConversions = false;
John McCallfe796dd2010-01-23 05:17:32 +00005164
5165 const FunctionProtoType* Proto;
5166 unsigned ArgIdx = ConvIdx;
5167
5168 if (Cand->IsSurrogate) {
5169 QualType ConvType
5170 = Cand->Surrogate->getConversionType().getNonReferenceType();
5171 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
5172 ConvType = ConvPtrType->getPointeeType();
5173 Proto = ConvType->getAs<FunctionProtoType>();
5174 ArgIdx--;
5175 } else if (Cand->Function) {
5176 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
5177 if (isa<CXXMethodDecl>(Cand->Function) &&
5178 !isa<CXXConstructorDecl>(Cand->Function))
5179 ArgIdx--;
5180 } else {
5181 // Builtin binary operator with a bad first conversion.
5182 assert(ConvCount <= 3);
5183 for (; ConvIdx != ConvCount; ++ConvIdx)
5184 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005185 = TryCopyInitialization(S, Args[ConvIdx],
5186 Cand->BuiltinTypes.ParamTypes[ConvIdx],
5187 SuppressUserConversions,
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005188 /*InOverloadResolution*/ true);
John McCallfe796dd2010-01-23 05:17:32 +00005189 return;
5190 }
5191
5192 // Fill in the rest of the conversions.
5193 unsigned NumArgsInProto = Proto->getNumArgs();
5194 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
5195 if (ArgIdx < NumArgsInProto)
5196 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005197 = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx),
5198 SuppressUserConversions,
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005199 /*InOverloadResolution=*/true);
John McCallfe796dd2010-01-23 05:17:32 +00005200 else
5201 Cand->Conversions[ConvIdx].setEllipsis();
5202 }
5203}
5204
John McCalld3224162010-01-08 00:58:21 +00005205} // end anonymous namespace
5206
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005207/// PrintOverloadCandidates - When overload resolution fails, prints
5208/// diagnostic messages containing the candidates in the candidate
John McCall12f97bc2010-01-08 04:41:39 +00005209/// set.
Mike Stump11289f42009-09-09 15:08:12 +00005210void
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005211Sema::PrintOverloadCandidates(OverloadCandidateSet& CandidateSet,
John McCall12f97bc2010-01-08 04:41:39 +00005212 OverloadCandidateDisplayKind OCD,
John McCallad907772010-01-12 07:18:19 +00005213 Expr **Args, unsigned NumArgs,
Fariborz Jahaniane7196432009-10-12 20:11:40 +00005214 const char *Opc,
Fariborz Jahanian29f9d392009-10-09 00:13:15 +00005215 SourceLocation OpLoc) {
John McCall12f97bc2010-01-08 04:41:39 +00005216 // Sort the candidates by viability and position. Sorting directly would
5217 // be prohibitive, so we make a set of pointers and sort those.
5218 llvm::SmallVector<OverloadCandidate*, 32> Cands;
5219 if (OCD == OCD_AllCandidates) Cands.reserve(CandidateSet.size());
5220 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
5221 LastCand = CandidateSet.end();
John McCallfe796dd2010-01-23 05:17:32 +00005222 Cand != LastCand; ++Cand) {
5223 if (Cand->Viable)
John McCall12f97bc2010-01-08 04:41:39 +00005224 Cands.push_back(Cand);
John McCallfe796dd2010-01-23 05:17:32 +00005225 else if (OCD == OCD_AllCandidates) {
5226 CompleteNonViableCandidate(*this, Cand, Args, NumArgs);
5227 Cands.push_back(Cand);
5228 }
5229 }
5230
John McCallad2587a2010-01-12 00:48:53 +00005231 std::sort(Cands.begin(), Cands.end(),
5232 CompareOverloadCandidatesForDisplay(*this));
John McCall12f97bc2010-01-08 04:41:39 +00005233
John McCall0d1da222010-01-12 00:44:57 +00005234 bool ReportedAmbiguousConversions = false;
John McCalld3224162010-01-08 00:58:21 +00005235
John McCall12f97bc2010-01-08 04:41:39 +00005236 llvm::SmallVectorImpl<OverloadCandidate*>::iterator I, E;
5237 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
5238 OverloadCandidate *Cand = *I;
Douglas Gregor4fc308b2008-11-21 02:54:28 +00005239
John McCalld3224162010-01-08 00:58:21 +00005240 if (Cand->Function)
John McCalle1ac8d12010-01-13 00:25:19 +00005241 NoteFunctionCandidate(*this, Cand, Args, NumArgs);
John McCalld3224162010-01-08 00:58:21 +00005242 else if (Cand->IsSurrogate)
5243 NoteSurrogateCandidate(*this, Cand);
5244
5245 // This a builtin candidate. We do not, in general, want to list
5246 // every possible builtin candidate.
John McCall0d1da222010-01-12 00:44:57 +00005247 else if (Cand->Viable) {
5248 // Generally we only see ambiguities including viable builtin
5249 // operators if overload resolution got screwed up by an
5250 // ambiguous user-defined conversion.
5251 //
5252 // FIXME: It's quite possible for different conversions to see
5253 // different ambiguities, though.
5254 if (!ReportedAmbiguousConversions) {
5255 NoteAmbiguousUserConversions(*this, OpLoc, Cand);
5256 ReportedAmbiguousConversions = true;
5257 }
John McCalld3224162010-01-08 00:58:21 +00005258
John McCall0d1da222010-01-12 00:44:57 +00005259 // If this is a viable builtin, print it.
John McCalld3224162010-01-08 00:58:21 +00005260 NoteBuiltinOperatorCandidate(*this, Opc, OpLoc, Cand);
Douglas Gregora11693b2008-11-12 17:17:38 +00005261 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005262 }
5263}
5264
John McCalla0296f72010-03-19 07:35:19 +00005265static bool CheckUnresolvedAccess(Sema &S, OverloadExpr *E, DeclAccessPair D) {
John McCall58cc69d2010-01-27 01:50:18 +00005266 if (isa<UnresolvedLookupExpr>(E))
John McCalla0296f72010-03-19 07:35:19 +00005267 return S.CheckUnresolvedLookupAccess(cast<UnresolvedLookupExpr>(E), D);
John McCall58cc69d2010-01-27 01:50:18 +00005268
John McCalla0296f72010-03-19 07:35:19 +00005269 return S.CheckUnresolvedMemberAccess(cast<UnresolvedMemberExpr>(E), D);
John McCall58cc69d2010-01-27 01:50:18 +00005270}
5271
Douglas Gregorcd695e52008-11-10 20:40:00 +00005272/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
5273/// an overloaded function (C++ [over.over]), where @p From is an
5274/// expression with overloaded function type and @p ToType is the type
5275/// we're trying to resolve to. For example:
5276///
5277/// @code
5278/// int f(double);
5279/// int f(int);
Mike Stump11289f42009-09-09 15:08:12 +00005280///
Douglas Gregorcd695e52008-11-10 20:40:00 +00005281/// int (*pfd)(double) = f; // selects f(double)
5282/// @endcode
5283///
5284/// This routine returns the resulting FunctionDecl if it could be
5285/// resolved, and NULL otherwise. When @p Complain is true, this
5286/// routine will emit diagnostics if there is an error.
5287FunctionDecl *
Sebastian Redl18f8ff62009-02-04 21:23:32 +00005288Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType,
John McCall16df1e52010-03-30 21:47:33 +00005289 bool Complain,
5290 DeclAccessPair &FoundResult) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00005291 QualType FunctionType = ToType;
Sebastian Redl18f8ff62009-02-04 21:23:32 +00005292 bool IsMember = false;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005293 if (const PointerType *ToTypePtr = ToType->getAs<PointerType>())
Douglas Gregorcd695e52008-11-10 20:40:00 +00005294 FunctionType = ToTypePtr->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005295 else if (const ReferenceType *ToTypeRef = ToType->getAs<ReferenceType>())
Daniel Dunbarb566c6c2009-02-26 19:13:44 +00005296 FunctionType = ToTypeRef->getPointeeType();
Sebastian Redl18f8ff62009-02-04 21:23:32 +00005297 else if (const MemberPointerType *MemTypePtr =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005298 ToType->getAs<MemberPointerType>()) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00005299 FunctionType = MemTypePtr->getPointeeType();
5300 IsMember = true;
5301 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00005302
Douglas Gregorcd695e52008-11-10 20:40:00 +00005303 // C++ [over.over]p1:
5304 // [...] [Note: any redundant set of parentheses surrounding the
5305 // overloaded function name is ignored (5.1). ]
Douglas Gregorcd695e52008-11-10 20:40:00 +00005306 // C++ [over.over]p1:
5307 // [...] The overloaded function name can be preceded by the &
5308 // operator.
John McCall1acbbb52010-02-02 06:20:04 +00005309 OverloadExpr *OvlExpr = OverloadExpr::find(From).getPointer();
5310 TemplateArgumentListInfo ETABuffer, *ExplicitTemplateArgs = 0;
5311 if (OvlExpr->hasExplicitTemplateArgs()) {
5312 OvlExpr->getExplicitTemplateArgs().copyInto(ETABuffer);
5313 ExplicitTemplateArgs = &ETABuffer;
Douglas Gregorcd695e52008-11-10 20:40:00 +00005314 }
Douglas Gregor064fdb22010-04-14 23:11:21 +00005315
5316 // We expect a pointer or reference to function, or a function pointer.
5317 FunctionType = Context.getCanonicalType(FunctionType).getUnqualifiedType();
5318 if (!FunctionType->isFunctionType()) {
5319 if (Complain)
5320 Diag(From->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
5321 << OvlExpr->getName() << ToType;
5322
5323 return 0;
5324 }
5325
5326 assert(From->getType() == Context.OverloadTy);
Douglas Gregorcd695e52008-11-10 20:40:00 +00005327
Douglas Gregorcd695e52008-11-10 20:40:00 +00005328 // Look through all of the overloaded functions, searching for one
5329 // whose type matches exactly.
John McCalla0296f72010-03-19 07:35:19 +00005330 llvm::SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
Douglas Gregorb242683d2010-04-01 18:32:35 +00005331 llvm::SmallVector<FunctionDecl *, 4> NonMatches;
5332
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005333 bool FoundNonTemplateFunction = false;
John McCall1acbbb52010-02-02 06:20:04 +00005334 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
5335 E = OvlExpr->decls_end(); I != E; ++I) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00005336 // Look through any using declarations to find the underlying function.
5337 NamedDecl *Fn = (*I)->getUnderlyingDecl();
5338
Douglas Gregorcd695e52008-11-10 20:40:00 +00005339 // C++ [over.over]p3:
5340 // Non-member functions and static member functions match
Sebastian Redl16d307d2009-02-05 12:33:33 +00005341 // targets of type "pointer-to-function" or "reference-to-function."
5342 // Nonstatic member functions match targets of
Sebastian Redl18f8ff62009-02-04 21:23:32 +00005343 // type "pointer-to-member-function."
5344 // Note that according to DR 247, the containing class does not matter.
Douglas Gregor9b146582009-07-08 20:55:45 +00005345
Mike Stump11289f42009-09-09 15:08:12 +00005346 if (FunctionTemplateDecl *FunctionTemplate
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00005347 = dyn_cast<FunctionTemplateDecl>(Fn)) {
Mike Stump11289f42009-09-09 15:08:12 +00005348 if (CXXMethodDecl *Method
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005349 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
Mike Stump11289f42009-09-09 15:08:12 +00005350 // Skip non-static function templates when converting to pointer, and
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005351 // static when converting to member pointer.
5352 if (Method->isStatic() == IsMember)
5353 continue;
5354 } else if (IsMember)
5355 continue;
Mike Stump11289f42009-09-09 15:08:12 +00005356
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005357 // C++ [over.over]p2:
Mike Stump11289f42009-09-09 15:08:12 +00005358 // If the name is a function template, template argument deduction is
5359 // done (14.8.2.2), and if the argument deduction succeeds, the
5360 // resulting template argument list is used to generate a single
5361 // function template specialization, which is added to the set of
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005362 // overloaded functions considered.
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00005363 // FIXME: We don't really want to build the specialization here, do we?
Douglas Gregor9b146582009-07-08 20:55:45 +00005364 FunctionDecl *Specialization = 0;
John McCallbc077cf2010-02-08 23:07:23 +00005365 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
Douglas Gregor9b146582009-07-08 20:55:45 +00005366 if (TemplateDeductionResult Result
John McCall1acbbb52010-02-02 06:20:04 +00005367 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor9b146582009-07-08 20:55:45 +00005368 FunctionType, Specialization, Info)) {
5369 // FIXME: make a note of the failed deduction for diagnostics.
5370 (void)Result;
5371 } else {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00005372 // FIXME: If the match isn't exact, shouldn't we just drop this as
5373 // a candidate? Find a testcase before changing the code.
Mike Stump11289f42009-09-09 15:08:12 +00005374 assert(FunctionType
Douglas Gregor9b146582009-07-08 20:55:45 +00005375 == Context.getCanonicalType(Specialization->getType()));
John McCalla0296f72010-03-19 07:35:19 +00005376 Matches.push_back(std::make_pair(I.getPair(),
5377 cast<FunctionDecl>(Specialization->getCanonicalDecl())));
Douglas Gregor9b146582009-07-08 20:55:45 +00005378 }
John McCalld14a8642009-11-21 08:51:07 +00005379
5380 continue;
Douglas Gregor9b146582009-07-08 20:55:45 +00005381 }
Mike Stump11289f42009-09-09 15:08:12 +00005382
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00005383 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00005384 // Skip non-static functions when converting to pointer, and static
5385 // when converting to member pointer.
5386 if (Method->isStatic() == IsMember)
Douglas Gregorcd695e52008-11-10 20:40:00 +00005387 continue;
Douglas Gregord3319842009-10-24 04:59:53 +00005388
5389 // If we have explicit template arguments, skip non-templates.
John McCall1acbbb52010-02-02 06:20:04 +00005390 if (OvlExpr->hasExplicitTemplateArgs())
Douglas Gregord3319842009-10-24 04:59:53 +00005391 continue;
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005392 } else if (IsMember)
Sebastian Redl18f8ff62009-02-04 21:23:32 +00005393 continue;
Douglas Gregorcd695e52008-11-10 20:40:00 +00005394
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00005395 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00005396 QualType ResultTy;
5397 if (Context.hasSameUnqualifiedType(FunctionType, FunDecl->getType()) ||
5398 IsNoReturnConversion(Context, FunDecl->getType(), FunctionType,
5399 ResultTy)) {
John McCalla0296f72010-03-19 07:35:19 +00005400 Matches.push_back(std::make_pair(I.getPair(),
5401 cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005402 FoundNonTemplateFunction = true;
5403 }
Mike Stump11289f42009-09-09 15:08:12 +00005404 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00005405 }
5406
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005407 // If there were 0 or 1 matches, we're done.
Douglas Gregor064fdb22010-04-14 23:11:21 +00005408 if (Matches.empty()) {
5409 if (Complain) {
5410 Diag(From->getLocStart(), diag::err_addr_ovl_no_viable)
5411 << OvlExpr->getName() << FunctionType;
5412 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
5413 E = OvlExpr->decls_end();
5414 I != E; ++I)
5415 if (FunctionDecl *F = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
5416 NoteOverloadCandidate(F);
5417 }
5418
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005419 return 0;
Douglas Gregor064fdb22010-04-14 23:11:21 +00005420 } else if (Matches.size() == 1) {
John McCalla0296f72010-03-19 07:35:19 +00005421 FunctionDecl *Result = Matches[0].second;
John McCall16df1e52010-03-30 21:47:33 +00005422 FoundResult = Matches[0].first;
Sebastian Redldf4b80e2009-10-17 21:12:09 +00005423 MarkDeclarationReferenced(From->getLocStart(), Result);
John McCall58cc69d2010-01-27 01:50:18 +00005424 if (Complain)
John McCall16df1e52010-03-30 21:47:33 +00005425 CheckAddressOfMemberAccess(OvlExpr, Matches[0].first);
Sebastian Redldf4b80e2009-10-17 21:12:09 +00005426 return Result;
5427 }
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005428
5429 // C++ [over.over]p4:
5430 // If more than one function is selected, [...]
Douglas Gregorfae1d712009-09-26 03:56:17 +00005431 if (!FoundNonTemplateFunction) {
Douglas Gregor05155d82009-08-21 23:19:43 +00005432 // [...] and any given function template specialization F1 is
5433 // eliminated if the set contains a second function template
5434 // specialization whose function template is more specialized
5435 // than the function template of F1 according to the partial
5436 // ordering rules of 14.5.5.2.
5437
5438 // The algorithm specified above is quadratic. We instead use a
5439 // two-pass algorithm (similar to the one used to identify the
5440 // best viable function in an overload set) that identifies the
5441 // best function template (if it exists).
John McCalla0296f72010-03-19 07:35:19 +00005442
5443 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
5444 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
5445 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
John McCall58cc69d2010-01-27 01:50:18 +00005446
5447 UnresolvedSetIterator Result =
John McCalla0296f72010-03-19 07:35:19 +00005448 getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(),
Sebastian Redldf4b80e2009-10-17 21:12:09 +00005449 TPOC_Other, From->getLocStart(),
5450 PDiag(),
5451 PDiag(diag::err_addr_ovl_ambiguous)
John McCalla0296f72010-03-19 07:35:19 +00005452 << Matches[0].second->getDeclName(),
John McCalle1ac8d12010-01-13 00:25:19 +00005453 PDiag(diag::note_ovl_candidate)
5454 << (unsigned) oc_function_template);
John McCalla0296f72010-03-19 07:35:19 +00005455 assert(Result != MatchesCopy.end() && "no most-specialized template");
John McCall58cc69d2010-01-27 01:50:18 +00005456 MarkDeclarationReferenced(From->getLocStart(), *Result);
John McCall16df1e52010-03-30 21:47:33 +00005457 FoundResult = Matches[Result - MatchesCopy.begin()].first;
5458 if (Complain)
5459 CheckUnresolvedAccess(*this, OvlExpr, FoundResult);
John McCall58cc69d2010-01-27 01:50:18 +00005460 return cast<FunctionDecl>(*Result);
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005461 }
Mike Stump11289f42009-09-09 15:08:12 +00005462
Douglas Gregorfae1d712009-09-26 03:56:17 +00005463 // [...] any function template specializations in the set are
5464 // eliminated if the set also contains a non-template function, [...]
John McCall58cc69d2010-01-27 01:50:18 +00005465 for (unsigned I = 0, N = Matches.size(); I != N; ) {
John McCalla0296f72010-03-19 07:35:19 +00005466 if (Matches[I].second->getPrimaryTemplate() == 0)
John McCall58cc69d2010-01-27 01:50:18 +00005467 ++I;
5468 else {
John McCalla0296f72010-03-19 07:35:19 +00005469 Matches[I] = Matches[--N];
5470 Matches.set_size(N);
John McCall58cc69d2010-01-27 01:50:18 +00005471 }
5472 }
Douglas Gregorfae1d712009-09-26 03:56:17 +00005473
Mike Stump11289f42009-09-09 15:08:12 +00005474 // [...] After such eliminations, if any, there shall remain exactly one
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005475 // selected function.
John McCall58cc69d2010-01-27 01:50:18 +00005476 if (Matches.size() == 1) {
John McCalla0296f72010-03-19 07:35:19 +00005477 MarkDeclarationReferenced(From->getLocStart(), Matches[0].second);
John McCall16df1e52010-03-30 21:47:33 +00005478 FoundResult = Matches[0].first;
John McCall58cc69d2010-01-27 01:50:18 +00005479 if (Complain)
John McCalla0296f72010-03-19 07:35:19 +00005480 CheckUnresolvedAccess(*this, OvlExpr, Matches[0].first);
5481 return cast<FunctionDecl>(Matches[0].second);
Sebastian Redldf4b80e2009-10-17 21:12:09 +00005482 }
Mike Stump11289f42009-09-09 15:08:12 +00005483
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005484 // FIXME: We should probably return the same thing that BestViableFunction
5485 // returns (even if we issue the diagnostics here).
5486 Diag(From->getLocStart(), diag::err_addr_ovl_ambiguous)
John McCalla0296f72010-03-19 07:35:19 +00005487 << Matches[0].second->getDeclName();
5488 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
5489 NoteOverloadCandidate(Matches[I].second);
Douglas Gregorcd695e52008-11-10 20:40:00 +00005490 return 0;
5491}
5492
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005493/// \brief Given an expression that refers to an overloaded function, try to
5494/// resolve that overloaded function expression down to a single function.
5495///
5496/// This routine can only resolve template-ids that refer to a single function
5497/// template, where that template-id refers to a single template whose template
5498/// arguments are either provided by the template-id or have defaults,
5499/// as described in C++0x [temp.arg.explicit]p3.
5500FunctionDecl *Sema::ResolveSingleFunctionTemplateSpecialization(Expr *From) {
5501 // C++ [over.over]p1:
5502 // [...] [Note: any redundant set of parentheses surrounding the
5503 // overloaded function name is ignored (5.1). ]
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005504 // C++ [over.over]p1:
5505 // [...] The overloaded function name can be preceded by the &
5506 // operator.
John McCall1acbbb52010-02-02 06:20:04 +00005507
5508 if (From->getType() != Context.OverloadTy)
5509 return 0;
5510
5511 OverloadExpr *OvlExpr = OverloadExpr::find(From).getPointer();
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005512
5513 // If we didn't actually find any template-ids, we're done.
John McCall1acbbb52010-02-02 06:20:04 +00005514 if (!OvlExpr->hasExplicitTemplateArgs())
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005515 return 0;
John McCall1acbbb52010-02-02 06:20:04 +00005516
5517 TemplateArgumentListInfo ExplicitTemplateArgs;
5518 OvlExpr->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005519
5520 // Look through all of the overloaded functions, searching for one
5521 // whose type matches exactly.
5522 FunctionDecl *Matched = 0;
John McCall1acbbb52010-02-02 06:20:04 +00005523 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
5524 E = OvlExpr->decls_end(); I != E; ++I) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005525 // C++0x [temp.arg.explicit]p3:
5526 // [...] In contexts where deduction is done and fails, or in contexts
5527 // where deduction is not done, if a template argument list is
5528 // specified and it, along with any default template arguments,
5529 // identifies a single function template specialization, then the
5530 // template-id is an lvalue for the function template specialization.
5531 FunctionTemplateDecl *FunctionTemplate = cast<FunctionTemplateDecl>(*I);
5532
5533 // C++ [over.over]p2:
5534 // If the name is a function template, template argument deduction is
5535 // done (14.8.2.2), and if the argument deduction succeeds, the
5536 // resulting template argument list is used to generate a single
5537 // function template specialization, which is added to the set of
5538 // overloaded functions considered.
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005539 FunctionDecl *Specialization = 0;
John McCallbc077cf2010-02-08 23:07:23 +00005540 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005541 if (TemplateDeductionResult Result
5542 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
5543 Specialization, Info)) {
5544 // FIXME: make a note of the failed deduction for diagnostics.
5545 (void)Result;
5546 continue;
5547 }
5548
5549 // Multiple matches; we can't resolve to a single declaration.
5550 if (Matched)
5551 return 0;
5552
5553 Matched = Specialization;
5554 }
5555
5556 return Matched;
5557}
5558
Douglas Gregorcabea402009-09-22 15:41:20 +00005559/// \brief Add a single candidate to the overload set.
5560static void AddOverloadedCallCandidate(Sema &S,
John McCalla0296f72010-03-19 07:35:19 +00005561 DeclAccessPair FoundDecl,
John McCall6b51f282009-11-23 01:53:49 +00005562 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00005563 Expr **Args, unsigned NumArgs,
5564 OverloadCandidateSet &CandidateSet,
5565 bool PartialOverloading) {
John McCalla0296f72010-03-19 07:35:19 +00005566 NamedDecl *Callee = FoundDecl.getDecl();
John McCalld14a8642009-11-21 08:51:07 +00005567 if (isa<UsingShadowDecl>(Callee))
5568 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
5569
Douglas Gregorcabea402009-09-22 15:41:20 +00005570 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
John McCall6b51f282009-11-23 01:53:49 +00005571 assert(!ExplicitTemplateArgs && "Explicit template arguments?");
John McCalla0296f72010-03-19 07:35:19 +00005572 S.AddOverloadCandidate(Func, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorb05275a2010-04-16 17:41:49 +00005573 false, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00005574 return;
John McCalld14a8642009-11-21 08:51:07 +00005575 }
5576
5577 if (FunctionTemplateDecl *FuncTemplate
5578 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCalla0296f72010-03-19 07:35:19 +00005579 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
5580 ExplicitTemplateArgs,
John McCalld14a8642009-11-21 08:51:07 +00005581 Args, NumArgs, CandidateSet);
John McCalld14a8642009-11-21 08:51:07 +00005582 return;
5583 }
5584
5585 assert(false && "unhandled case in overloaded call candidate");
5586
5587 // do nothing?
Douglas Gregorcabea402009-09-22 15:41:20 +00005588}
5589
5590/// \brief Add the overload candidates named by callee and/or found by argument
5591/// dependent lookup to the given overload set.
John McCall57500772009-12-16 12:17:52 +00005592void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Douglas Gregorcabea402009-09-22 15:41:20 +00005593 Expr **Args, unsigned NumArgs,
5594 OverloadCandidateSet &CandidateSet,
5595 bool PartialOverloading) {
John McCalld14a8642009-11-21 08:51:07 +00005596
5597#ifndef NDEBUG
5598 // Verify that ArgumentDependentLookup is consistent with the rules
5599 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregorcabea402009-09-22 15:41:20 +00005600 //
Douglas Gregorcabea402009-09-22 15:41:20 +00005601 // Let X be the lookup set produced by unqualified lookup (3.4.1)
5602 // and let Y be the lookup set produced by argument dependent
5603 // lookup (defined as follows). If X contains
5604 //
5605 // -- a declaration of a class member, or
5606 //
5607 // -- a block-scope function declaration that is not a
John McCalld14a8642009-11-21 08:51:07 +00005608 // using-declaration, or
Douglas Gregorcabea402009-09-22 15:41:20 +00005609 //
5610 // -- a declaration that is neither a function or a function
5611 // template
5612 //
5613 // then Y is empty.
John McCalld14a8642009-11-21 08:51:07 +00005614
John McCall57500772009-12-16 12:17:52 +00005615 if (ULE->requiresADL()) {
5616 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
5617 E = ULE->decls_end(); I != E; ++I) {
5618 assert(!(*I)->getDeclContext()->isRecord());
5619 assert(isa<UsingShadowDecl>(*I) ||
5620 !(*I)->getDeclContext()->isFunctionOrMethod());
5621 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCalld14a8642009-11-21 08:51:07 +00005622 }
5623 }
5624#endif
5625
John McCall57500772009-12-16 12:17:52 +00005626 // It would be nice to avoid this copy.
5627 TemplateArgumentListInfo TABuffer;
5628 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
5629 if (ULE->hasExplicitTemplateArgs()) {
5630 ULE->copyTemplateArgumentsInto(TABuffer);
5631 ExplicitTemplateArgs = &TABuffer;
5632 }
5633
5634 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
5635 E = ULE->decls_end(); I != E; ++I)
John McCalla0296f72010-03-19 07:35:19 +00005636 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs,
John McCalld14a8642009-11-21 08:51:07 +00005637 Args, NumArgs, CandidateSet,
Douglas Gregorcabea402009-09-22 15:41:20 +00005638 PartialOverloading);
John McCalld14a8642009-11-21 08:51:07 +00005639
John McCall57500772009-12-16 12:17:52 +00005640 if (ULE->requiresADL())
John McCall4c4c1df2010-01-26 03:27:55 +00005641 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
5642 Args, NumArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00005643 ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00005644 CandidateSet,
5645 PartialOverloading);
5646}
John McCalld681c392009-12-16 08:11:27 +00005647
John McCall57500772009-12-16 12:17:52 +00005648static Sema::OwningExprResult Destroy(Sema &SemaRef, Expr *Fn,
5649 Expr **Args, unsigned NumArgs) {
5650 Fn->Destroy(SemaRef.Context);
5651 for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
5652 Args[Arg]->Destroy(SemaRef.Context);
5653 return SemaRef.ExprError();
5654}
5655
John McCalld681c392009-12-16 08:11:27 +00005656/// Attempts to recover from a call where no functions were found.
5657///
5658/// Returns true if new candidates were found.
John McCall57500772009-12-16 12:17:52 +00005659static Sema::OwningExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +00005660BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall57500772009-12-16 12:17:52 +00005661 UnresolvedLookupExpr *ULE,
5662 SourceLocation LParenLoc,
5663 Expr **Args, unsigned NumArgs,
5664 SourceLocation *CommaLocs,
5665 SourceLocation RParenLoc) {
John McCalld681c392009-12-16 08:11:27 +00005666
5667 CXXScopeSpec SS;
5668 if (ULE->getQualifier()) {
5669 SS.setScopeRep(ULE->getQualifier());
5670 SS.setRange(ULE->getQualifierRange());
5671 }
5672
John McCall57500772009-12-16 12:17:52 +00005673 TemplateArgumentListInfo TABuffer;
5674 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
5675 if (ULE->hasExplicitTemplateArgs()) {
5676 ULE->copyTemplateArgumentsInto(TABuffer);
5677 ExplicitTemplateArgs = &TABuffer;
5678 }
5679
John McCalld681c392009-12-16 08:11:27 +00005680 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
5681 Sema::LookupOrdinaryName);
Douglas Gregor2fb18b72010-04-14 20:27:54 +00005682 if (SemaRef.DiagnoseEmptyLookup(S, SS, R))
John McCall57500772009-12-16 12:17:52 +00005683 return Destroy(SemaRef, Fn, Args, NumArgs);
John McCalld681c392009-12-16 08:11:27 +00005684
John McCall57500772009-12-16 12:17:52 +00005685 assert(!R.empty() && "lookup results empty despite recovery");
5686
5687 // Build an implicit member call if appropriate. Just drop the
5688 // casts and such from the call, we don't really care.
5689 Sema::OwningExprResult NewFn = SemaRef.ExprError();
5690 if ((*R.begin())->isCXXClassMember())
5691 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, R, ExplicitTemplateArgs);
5692 else if (ExplicitTemplateArgs)
5693 NewFn = SemaRef.BuildTemplateIdExpr(SS, R, false, *ExplicitTemplateArgs);
5694 else
5695 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
5696
5697 if (NewFn.isInvalid())
5698 return Destroy(SemaRef, Fn, Args, NumArgs);
5699
5700 Fn->Destroy(SemaRef.Context);
5701
5702 // This shouldn't cause an infinite loop because we're giving it
5703 // an expression with non-empty lookup results, which should never
5704 // end up here.
5705 return SemaRef.ActOnCallExpr(/*Scope*/ 0, move(NewFn), LParenLoc,
5706 Sema::MultiExprArg(SemaRef, (void**) Args, NumArgs),
5707 CommaLocs, RParenLoc);
John McCalld681c392009-12-16 08:11:27 +00005708}
Douglas Gregorcabea402009-09-22 15:41:20 +00005709
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005710/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregore254f902009-02-04 00:32:51 +00005711/// (which eventually refers to the declaration Func) and the call
5712/// arguments Args/NumArgs, attempt to resolve the function call down
5713/// to a specific function. If overload resolution succeeds, returns
5714/// the function declaration produced by overload
Douglas Gregora60a6912008-11-26 06:01:48 +00005715/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005716/// arguments and Fn, and returns NULL.
John McCall57500772009-12-16 12:17:52 +00005717Sema::OwningExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +00005718Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
John McCall57500772009-12-16 12:17:52 +00005719 SourceLocation LParenLoc,
5720 Expr **Args, unsigned NumArgs,
5721 SourceLocation *CommaLocs,
5722 SourceLocation RParenLoc) {
5723#ifndef NDEBUG
5724 if (ULE->requiresADL()) {
5725 // To do ADL, we must have found an unqualified name.
5726 assert(!ULE->getQualifier() && "qualified name with ADL");
5727
5728 // We don't perform ADL for implicit declarations of builtins.
5729 // Verify that this was correctly set up.
5730 FunctionDecl *F;
5731 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
5732 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
5733 F->getBuiltinID() && F->isImplicit())
5734 assert(0 && "performing ADL for builtin");
5735
5736 // We don't perform ADL in C.
5737 assert(getLangOptions().CPlusPlus && "ADL enabled in C");
5738 }
5739#endif
5740
John McCallbc077cf2010-02-08 23:07:23 +00005741 OverloadCandidateSet CandidateSet(Fn->getExprLoc());
Douglas Gregorb8a9a412009-02-04 15:01:18 +00005742
John McCall57500772009-12-16 12:17:52 +00005743 // Add the functions denoted by the callee to the set of candidate
5744 // functions, including those from argument-dependent lookup.
5745 AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet);
John McCalld681c392009-12-16 08:11:27 +00005746
5747 // If we found nothing, try to recover.
5748 // AddRecoveryCallCandidates diagnoses the error itself, so we just
5749 // bailout out if it fails.
John McCall57500772009-12-16 12:17:52 +00005750 if (CandidateSet.empty())
Douglas Gregor2fb18b72010-04-14 20:27:54 +00005751 return BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc, Args, NumArgs,
John McCall57500772009-12-16 12:17:52 +00005752 CommaLocs, RParenLoc);
John McCalld681c392009-12-16 08:11:27 +00005753
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005754 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005755 switch (BestViableFunction(CandidateSet, Fn->getLocStart(), Best)) {
John McCall57500772009-12-16 12:17:52 +00005756 case OR_Success: {
5757 FunctionDecl *FDecl = Best->Function;
John McCalla0296f72010-03-19 07:35:19 +00005758 CheckUnresolvedLookupAccess(ULE, Best->FoundDecl);
John McCall16df1e52010-03-30 21:47:33 +00005759 Fn = FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl);
John McCall57500772009-12-16 12:17:52 +00005760 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs, RParenLoc);
5761 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005762
5763 case OR_No_Viable_Function:
Chris Lattner45d9d602009-02-17 07:29:20 +00005764 Diag(Fn->getSourceRange().getBegin(),
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005765 diag::err_ovl_no_viable_function_in_call)
John McCall57500772009-12-16 12:17:52 +00005766 << ULE->getName() << Fn->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00005767 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005768 break;
5769
5770 case OR_Ambiguous:
5771 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
John McCall57500772009-12-16 12:17:52 +00005772 << ULE->getName() << Fn->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00005773 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005774 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00005775
5776 case OR_Deleted:
5777 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
5778 << Best->Function->isDeleted()
John McCall57500772009-12-16 12:17:52 +00005779 << ULE->getName()
Douglas Gregor171c45a2009-02-18 21:56:37 +00005780 << Fn->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00005781 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00005782 break;
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005783 }
5784
5785 // Overload resolution failed. Destroy all of the subexpressions and
5786 // return NULL.
5787 Fn->Destroy(Context);
5788 for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
5789 Args[Arg]->Destroy(Context);
John McCall57500772009-12-16 12:17:52 +00005790 return ExprError();
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005791}
5792
John McCall4c4c1df2010-01-26 03:27:55 +00005793static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall283b9012009-11-22 00:44:51 +00005794 return Functions.size() > 1 ||
5795 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
5796}
5797
Douglas Gregor084d8552009-03-13 23:49:33 +00005798/// \brief Create a unary operation that may resolve to an overloaded
5799/// operator.
5800///
5801/// \param OpLoc The location of the operator itself (e.g., '*').
5802///
5803/// \param OpcIn The UnaryOperator::Opcode that describes this
5804/// operator.
5805///
5806/// \param Functions The set of non-member functions that will be
5807/// considered by overload resolution. The caller needs to build this
5808/// set based on the context using, e.g.,
5809/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
5810/// set should not contain any member functions; those will be added
5811/// by CreateOverloadedUnaryOp().
5812///
5813/// \param input The input argument.
John McCall4c4c1df2010-01-26 03:27:55 +00005814Sema::OwningExprResult
5815Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
5816 const UnresolvedSetImpl &Fns,
5817 ExprArg input) {
Douglas Gregor084d8552009-03-13 23:49:33 +00005818 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
5819 Expr *Input = (Expr *)input.get();
5820
5821 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
5822 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
5823 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
5824
5825 Expr *Args[2] = { Input, 0 };
5826 unsigned NumArgs = 1;
Mike Stump11289f42009-09-09 15:08:12 +00005827
Douglas Gregor084d8552009-03-13 23:49:33 +00005828 // For post-increment and post-decrement, add the implicit '0' as
5829 // the second argument, so that we know this is a post-increment or
5830 // post-decrement.
5831 if (Opc == UnaryOperator::PostInc || Opc == UnaryOperator::PostDec) {
5832 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Mike Stump11289f42009-09-09 15:08:12 +00005833 Args[1] = new (Context) IntegerLiteral(Zero, Context.IntTy,
Douglas Gregor084d8552009-03-13 23:49:33 +00005834 SourceLocation());
5835 NumArgs = 2;
5836 }
5837
5838 if (Input->isTypeDependent()) {
John McCall58cc69d2010-01-27 01:50:18 +00005839 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +00005840 UnresolvedLookupExpr *Fn
John McCall58cc69d2010-01-27 01:50:18 +00005841 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
John McCalle66edc12009-11-24 19:00:30 +00005842 0, SourceRange(), OpName, OpLoc,
John McCall4c4c1df2010-01-26 03:27:55 +00005843 /*ADL*/ true, IsOverloaded(Fns));
5844 Fn->addDecls(Fns.begin(), Fns.end());
Mike Stump11289f42009-09-09 15:08:12 +00005845
Douglas Gregor084d8552009-03-13 23:49:33 +00005846 input.release();
5847 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
5848 &Args[0], NumArgs,
5849 Context.DependentTy,
5850 OpLoc));
5851 }
5852
5853 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00005854 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00005855
5856 // Add the candidates from the given function set.
John McCall4c4c1df2010-01-26 03:27:55 +00005857 AddFunctionCandidates(Fns, &Args[0], NumArgs, CandidateSet, false);
Douglas Gregor084d8552009-03-13 23:49:33 +00005858
5859 // Add operator candidates that are member functions.
5860 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
5861
John McCall4c4c1df2010-01-26 03:27:55 +00005862 // Add candidates from ADL.
5863 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Douglas Gregor6ec89d42010-02-05 05:15:43 +00005864 Args, NumArgs,
John McCall4c4c1df2010-01-26 03:27:55 +00005865 /*ExplicitTemplateArgs*/ 0,
5866 CandidateSet);
5867
Douglas Gregor084d8552009-03-13 23:49:33 +00005868 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00005869 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +00005870
5871 // Perform overload resolution.
5872 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005873 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregor084d8552009-03-13 23:49:33 +00005874 case OR_Success: {
5875 // We found a built-in operator or an overloaded operator.
5876 FunctionDecl *FnDecl = Best->Function;
Mike Stump11289f42009-09-09 15:08:12 +00005877
Douglas Gregor084d8552009-03-13 23:49:33 +00005878 if (FnDecl) {
5879 // We matched an overloaded operator. Build a call to that
5880 // operator.
Mike Stump11289f42009-09-09 15:08:12 +00005881
Douglas Gregor084d8552009-03-13 23:49:33 +00005882 // Convert the arguments.
5883 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCalla0296f72010-03-19 07:35:19 +00005884 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +00005885
John McCall16df1e52010-03-30 21:47:33 +00005886 if (PerformObjectArgumentInitialization(Input, /*Qualifier=*/0,
5887 Best->FoundDecl, Method))
Douglas Gregor084d8552009-03-13 23:49:33 +00005888 return ExprError();
5889 } else {
5890 // Convert the arguments.
Douglas Gregore6600372009-12-23 17:40:29 +00005891 OwningExprResult InputInit
5892 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Douglas Gregor8d48e9a2009-12-23 00:02:00 +00005893 FnDecl->getParamDecl(0)),
Douglas Gregore6600372009-12-23 17:40:29 +00005894 SourceLocation(),
5895 move(input));
5896 if (InputInit.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +00005897 return ExprError();
Douglas Gregor8d48e9a2009-12-23 00:02:00 +00005898
Douglas Gregore6600372009-12-23 17:40:29 +00005899 input = move(InputInit);
Douglas Gregor8d48e9a2009-12-23 00:02:00 +00005900 Input = (Expr *)input.get();
Douglas Gregor084d8552009-03-13 23:49:33 +00005901 }
5902
5903 // Determine the result type
Anders Carlssonf64a3da2009-10-13 21:19:37 +00005904 QualType ResultTy = FnDecl->getResultType().getNonReferenceType();
Mike Stump11289f42009-09-09 15:08:12 +00005905
Douglas Gregor084d8552009-03-13 23:49:33 +00005906 // Build the actual expression node.
5907 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
5908 SourceLocation());
5909 UsualUnaryConversions(FnExpr);
Mike Stump11289f42009-09-09 15:08:12 +00005910
Douglas Gregor084d8552009-03-13 23:49:33 +00005911 input.release();
Eli Friedman030eee42009-11-18 03:58:17 +00005912 Args[0] = Input;
Anders Carlssonf64a3da2009-10-13 21:19:37 +00005913 ExprOwningPtr<CallExpr> TheCall(this,
5914 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
Eli Friedman030eee42009-11-18 03:58:17 +00005915 Args, NumArgs, ResultTy, OpLoc));
Anders Carlssonf64a3da2009-10-13 21:19:37 +00005916
5917 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall.get(),
5918 FnDecl))
5919 return ExprError();
5920
5921 return MaybeBindToTemporary(TheCall.release());
Douglas Gregor084d8552009-03-13 23:49:33 +00005922 } else {
5923 // We matched a built-in operator. Convert the arguments, then
5924 // break out so that we will build the appropriate built-in
5925 // operator node.
5926 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00005927 Best->Conversions[0], AA_Passing))
Douglas Gregor084d8552009-03-13 23:49:33 +00005928 return ExprError();
5929
5930 break;
5931 }
5932 }
5933
5934 case OR_No_Viable_Function:
5935 // No viable function; fall through to handling this as a
5936 // built-in operator, which will produce an error message for us.
5937 break;
5938
5939 case OR_Ambiguous:
5940 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
5941 << UnaryOperator::getOpcodeStr(Opc)
5942 << Input->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00005943 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, NumArgs,
Fariborz Jahaniane7196432009-10-12 20:11:40 +00005944 UnaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00005945 return ExprError();
5946
5947 case OR_Deleted:
5948 Diag(OpLoc, diag::err_ovl_deleted_oper)
5949 << Best->Function->isDeleted()
5950 << UnaryOperator::getOpcodeStr(Opc)
5951 << Input->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00005952 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor084d8552009-03-13 23:49:33 +00005953 return ExprError();
5954 }
5955
5956 // Either we found no viable overloaded operator or we matched a
5957 // built-in operator. In either case, fall through to trying to
5958 // build a built-in operation.
5959 input.release();
5960 return CreateBuiltinUnaryOp(OpLoc, Opc, Owned(Input));
5961}
5962
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005963/// \brief Create a binary operation that may resolve to an overloaded
5964/// operator.
5965///
5966/// \param OpLoc The location of the operator itself (e.g., '+').
5967///
5968/// \param OpcIn The BinaryOperator::Opcode that describes this
5969/// operator.
5970///
5971/// \param Functions The set of non-member functions that will be
5972/// considered by overload resolution. The caller needs to build this
5973/// set based on the context using, e.g.,
5974/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
5975/// set should not contain any member functions; those will be added
5976/// by CreateOverloadedBinOp().
5977///
5978/// \param LHS Left-hand argument.
5979/// \param RHS Right-hand argument.
Mike Stump11289f42009-09-09 15:08:12 +00005980Sema::OwningExprResult
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005981Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump11289f42009-09-09 15:08:12 +00005982 unsigned OpcIn,
John McCall4c4c1df2010-01-26 03:27:55 +00005983 const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005984 Expr *LHS, Expr *RHS) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005985 Expr *Args[2] = { LHS, RHS };
Douglas Gregore9899d92009-08-26 17:08:25 +00005986 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005987
5988 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
5989 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
5990 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
5991
5992 // If either side is type-dependent, create an appropriate dependent
5993 // expression.
Douglas Gregore9899d92009-08-26 17:08:25 +00005994 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall4c4c1df2010-01-26 03:27:55 +00005995 if (Fns.empty()) {
Douglas Gregor5287f092009-11-05 00:51:44 +00005996 // If there are no functions to store, just build a dependent
5997 // BinaryOperator or CompoundAssignment.
5998 if (Opc <= BinaryOperator::Assign || Opc > BinaryOperator::OrAssign)
5999 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
6000 Context.DependentTy, OpLoc));
6001
6002 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
6003 Context.DependentTy,
6004 Context.DependentTy,
6005 Context.DependentTy,
6006 OpLoc));
6007 }
John McCall4c4c1df2010-01-26 03:27:55 +00006008
6009 // FIXME: save results of ADL from here?
John McCall58cc69d2010-01-27 01:50:18 +00006010 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +00006011 UnresolvedLookupExpr *Fn
John McCall58cc69d2010-01-27 01:50:18 +00006012 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
John McCalle66edc12009-11-24 19:00:30 +00006013 0, SourceRange(), OpName, OpLoc,
John McCall4c4c1df2010-01-26 03:27:55 +00006014 /*ADL*/ true, IsOverloaded(Fns));
Mike Stump11289f42009-09-09 15:08:12 +00006015
John McCall4c4c1df2010-01-26 03:27:55 +00006016 Fn->addDecls(Fns.begin(), Fns.end());
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006017 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Mike Stump11289f42009-09-09 15:08:12 +00006018 Args, 2,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006019 Context.DependentTy,
6020 OpLoc));
6021 }
6022
6023 // If this is the .* operator, which is not overloadable, just
6024 // create a built-in binary operator.
6025 if (Opc == BinaryOperator::PtrMemD)
Douglas Gregore9899d92009-08-26 17:08:25 +00006026 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006027
Sebastian Redl6a96bf72009-11-18 23:10:33 +00006028 // If this is the assignment operator, we only perform overload resolution
6029 // if the left-hand side is a class or enumeration type. This is actually
6030 // a hack. The standard requires that we do overload resolution between the
6031 // various built-in candidates, but as DR507 points out, this can lead to
6032 // problems. So we do it this way, which pretty much follows what GCC does.
6033 // Note that we go the traditional code path for compound assignment forms.
6034 if (Opc==BinaryOperator::Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregore9899d92009-08-26 17:08:25 +00006035 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006036
Douglas Gregor084d8552009-03-13 23:49:33 +00006037 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00006038 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006039
6040 // Add the candidates from the given function set.
John McCall4c4c1df2010-01-26 03:27:55 +00006041 AddFunctionCandidates(Fns, Args, 2, CandidateSet, false);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006042
6043 // Add operator candidates that are member functions.
6044 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
6045
John McCall4c4c1df2010-01-26 03:27:55 +00006046 // Add candidates from ADL.
6047 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
6048 Args, 2,
6049 /*ExplicitTemplateArgs*/ 0,
6050 CandidateSet);
6051
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006052 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00006053 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006054
6055 // Perform overload resolution.
6056 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006057 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00006058 case OR_Success: {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006059 // We found a built-in operator or an overloaded operator.
6060 FunctionDecl *FnDecl = Best->Function;
6061
6062 if (FnDecl) {
6063 // We matched an overloaded operator. Build a call to that
6064 // operator.
6065
6066 // Convert the arguments.
6067 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCallb3a44002010-01-28 01:42:12 +00006068 // Best->Access is only meaningful for class members.
John McCalla0296f72010-03-19 07:35:19 +00006069 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +00006070
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00006071 OwningExprResult Arg1
6072 = PerformCopyInitialization(
6073 InitializedEntity::InitializeParameter(
6074 FnDecl->getParamDecl(0)),
6075 SourceLocation(),
6076 Owned(Args[1]));
6077 if (Arg1.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006078 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00006079
Douglas Gregorcc3f3252010-03-03 23:55:11 +00006080 if (PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
John McCall16df1e52010-03-30 21:47:33 +00006081 Best->FoundDecl, Method))
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00006082 return ExprError();
6083
6084 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006085 } else {
6086 // Convert the arguments.
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00006087 OwningExprResult Arg0
6088 = PerformCopyInitialization(
6089 InitializedEntity::InitializeParameter(
6090 FnDecl->getParamDecl(0)),
6091 SourceLocation(),
6092 Owned(Args[0]));
6093 if (Arg0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006094 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00006095
6096 OwningExprResult Arg1
6097 = PerformCopyInitialization(
6098 InitializedEntity::InitializeParameter(
6099 FnDecl->getParamDecl(1)),
6100 SourceLocation(),
6101 Owned(Args[1]));
6102 if (Arg1.isInvalid())
6103 return ExprError();
6104 Args[0] = LHS = Arg0.takeAs<Expr>();
6105 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006106 }
6107
6108 // Determine the result type
6109 QualType ResultTy
John McCall9dd450b2009-09-21 23:43:11 +00006110 = FnDecl->getType()->getAs<FunctionType>()->getResultType();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006111 ResultTy = ResultTy.getNonReferenceType();
6112
6113 // Build the actual expression node.
6114 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Argyrios Kyrtzidisef1c1e52009-07-14 03:19:38 +00006115 OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006116 UsualUnaryConversions(FnExpr);
6117
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00006118 ExprOwningPtr<CXXOperatorCallExpr>
6119 TheCall(this, new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
6120 Args, 2, ResultTy,
6121 OpLoc));
6122
6123 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall.get(),
6124 FnDecl))
6125 return ExprError();
6126
6127 return MaybeBindToTemporary(TheCall.release());
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006128 } else {
6129 // We matched a built-in operator. Convert the arguments, then
6130 // break out so that we will build the appropriate built-in
6131 // operator node.
Douglas Gregore9899d92009-08-26 17:08:25 +00006132 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00006133 Best->Conversions[0], AA_Passing) ||
Douglas Gregore9899d92009-08-26 17:08:25 +00006134 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00006135 Best->Conversions[1], AA_Passing))
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006136 return ExprError();
6137
6138 break;
6139 }
6140 }
6141
Douglas Gregor66950a32009-09-30 21:46:01 +00006142 case OR_No_Viable_Function: {
6143 // C++ [over.match.oper]p9:
6144 // If the operator is the operator , [...] and there are no
6145 // viable functions, then the operator is assumed to be the
6146 // built-in operator and interpreted according to clause 5.
6147 if (Opc == BinaryOperator::Comma)
6148 break;
6149
Sebastian Redl027de2a2009-05-21 11:50:50 +00006150 // For class as left operand for assignment or compound assigment operator
6151 // do not fall through to handling in built-in, but report that no overloaded
6152 // assignment operator found
Douglas Gregor66950a32009-09-30 21:46:01 +00006153 OwningExprResult Result = ExprError();
6154 if (Args[0]->getType()->isRecordType() &&
6155 Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign) {
Sebastian Redl027de2a2009-05-21 11:50:50 +00006156 Diag(OpLoc, diag::err_ovl_no_viable_oper)
6157 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00006158 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor66950a32009-09-30 21:46:01 +00006159 } else {
6160 // No viable function; try to create a built-in operation, which will
6161 // produce an error. Then, show the non-viable candidates.
6162 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl027de2a2009-05-21 11:50:50 +00006163 }
Douglas Gregor66950a32009-09-30 21:46:01 +00006164 assert(Result.isInvalid() &&
6165 "C++ binary operator overloading is missing candidates!");
6166 if (Result.isInvalid())
John McCallad907772010-01-12 07:18:19 +00006167 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2,
Fariborz Jahaniane7196432009-10-12 20:11:40 +00006168 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor66950a32009-09-30 21:46:01 +00006169 return move(Result);
6170 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006171
6172 case OR_Ambiguous:
6173 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
6174 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00006175 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006176 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, 2,
Fariborz Jahaniane7196432009-10-12 20:11:40 +00006177 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006178 return ExprError();
6179
6180 case OR_Deleted:
6181 Diag(OpLoc, diag::err_ovl_deleted_oper)
6182 << Best->Function->isDeleted()
6183 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00006184 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006185 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006186 return ExprError();
John McCall0d1da222010-01-12 00:44:57 +00006187 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006188
Douglas Gregor66950a32009-09-30 21:46:01 +00006189 // We matched a built-in operator; build it.
Douglas Gregore9899d92009-08-26 17:08:25 +00006190 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006191}
6192
Sebastian Redladba46e2009-10-29 20:17:01 +00006193Action::OwningExprResult
6194Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
6195 SourceLocation RLoc,
6196 ExprArg Base, ExprArg Idx) {
6197 Expr *Args[2] = { static_cast<Expr*>(Base.get()),
6198 static_cast<Expr*>(Idx.get()) };
6199 DeclarationName OpName =
6200 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
6201
6202 // If either side is type-dependent, create an appropriate dependent
6203 // expression.
6204 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
6205
John McCall58cc69d2010-01-27 01:50:18 +00006206 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +00006207 UnresolvedLookupExpr *Fn
John McCall58cc69d2010-01-27 01:50:18 +00006208 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
John McCalle66edc12009-11-24 19:00:30 +00006209 0, SourceRange(), OpName, LLoc,
John McCall283b9012009-11-22 00:44:51 +00006210 /*ADL*/ true, /*Overloaded*/ false);
John McCalle66edc12009-11-24 19:00:30 +00006211 // Can't add any actual overloads yet
Sebastian Redladba46e2009-10-29 20:17:01 +00006212
6213 Base.release();
6214 Idx.release();
6215 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
6216 Args, 2,
6217 Context.DependentTy,
6218 RLoc));
6219 }
6220
6221 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00006222 OverloadCandidateSet CandidateSet(LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00006223
6224 // Subscript can only be overloaded as a member function.
6225
6226 // Add operator candidates that are member functions.
6227 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
6228
6229 // Add builtin operator candidates.
6230 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
6231
6232 // Perform overload resolution.
6233 OverloadCandidateSet::iterator Best;
6234 switch (BestViableFunction(CandidateSet, LLoc, Best)) {
6235 case OR_Success: {
6236 // We found a built-in operator or an overloaded operator.
6237 FunctionDecl *FnDecl = Best->Function;
6238
6239 if (FnDecl) {
6240 // We matched an overloaded operator. Build a call to that
6241 // operator.
6242
John McCalla0296f72010-03-19 07:35:19 +00006243 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCall58cc69d2010-01-27 01:50:18 +00006244
Sebastian Redladba46e2009-10-29 20:17:01 +00006245 // Convert the arguments.
6246 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00006247 if (PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
John McCall16df1e52010-03-30 21:47:33 +00006248 Best->FoundDecl, Method))
Sebastian Redladba46e2009-10-29 20:17:01 +00006249 return ExprError();
6250
Anders Carlssona68e51e2010-01-29 18:37:50 +00006251 // Convert the arguments.
6252 OwningExprResult InputInit
6253 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
6254 FnDecl->getParamDecl(0)),
6255 SourceLocation(),
6256 Owned(Args[1]));
6257 if (InputInit.isInvalid())
6258 return ExprError();
6259
6260 Args[1] = InputInit.takeAs<Expr>();
6261
Sebastian Redladba46e2009-10-29 20:17:01 +00006262 // Determine the result type
6263 QualType ResultTy
6264 = FnDecl->getType()->getAs<FunctionType>()->getResultType();
6265 ResultTy = ResultTy.getNonReferenceType();
6266
6267 // Build the actual expression node.
6268 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
6269 LLoc);
6270 UsualUnaryConversions(FnExpr);
6271
6272 Base.release();
6273 Idx.release();
6274 ExprOwningPtr<CXXOperatorCallExpr>
6275 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
6276 FnExpr, Args, 2,
6277 ResultTy, RLoc));
6278
6279 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall.get(),
6280 FnDecl))
6281 return ExprError();
6282
6283 return MaybeBindToTemporary(TheCall.release());
6284 } else {
6285 // We matched a built-in operator. Convert the arguments, then
6286 // break out so that we will build the appropriate built-in
6287 // operator node.
6288 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00006289 Best->Conversions[0], AA_Passing) ||
Sebastian Redladba46e2009-10-29 20:17:01 +00006290 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00006291 Best->Conversions[1], AA_Passing))
Sebastian Redladba46e2009-10-29 20:17:01 +00006292 return ExprError();
6293
6294 break;
6295 }
6296 }
6297
6298 case OR_No_Viable_Function: {
John McCall02374852010-01-07 02:04:15 +00006299 if (CandidateSet.empty())
6300 Diag(LLoc, diag::err_ovl_no_oper)
6301 << Args[0]->getType() << /*subscript*/ 0
6302 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
6303 else
6304 Diag(LLoc, diag::err_ovl_no_viable_subscript)
6305 << Args[0]->getType()
6306 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006307 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2,
John McCall02374852010-01-07 02:04:15 +00006308 "[]", LLoc);
6309 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +00006310 }
6311
6312 case OR_Ambiguous:
6313 Diag(LLoc, diag::err_ovl_ambiguous_oper)
6314 << "[]" << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006315 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, 2,
Sebastian Redladba46e2009-10-29 20:17:01 +00006316 "[]", LLoc);
6317 return ExprError();
6318
6319 case OR_Deleted:
6320 Diag(LLoc, diag::err_ovl_deleted_oper)
6321 << Best->Function->isDeleted() << "[]"
6322 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006323 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2,
John McCall12f97bc2010-01-08 04:41:39 +00006324 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00006325 return ExprError();
6326 }
6327
6328 // We matched a built-in operator; build it.
6329 Base.release();
6330 Idx.release();
6331 return CreateBuiltinArraySubscriptExpr(Owned(Args[0]), LLoc,
6332 Owned(Args[1]), RLoc);
6333}
6334
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006335/// BuildCallToMemberFunction - Build a call to a member
6336/// function. MemExpr is the expression that refers to the member
6337/// function (and includes the object parameter), Args/NumArgs are the
6338/// arguments to the function call (not including the object
6339/// parameter). The caller needs to validate that the member
6340/// expression refers to a member function or an overloaded member
6341/// function.
John McCall2d74de92009-12-01 22:10:20 +00006342Sema::OwningExprResult
Mike Stump11289f42009-09-09 15:08:12 +00006343Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
6344 SourceLocation LParenLoc, Expr **Args,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006345 unsigned NumArgs, SourceLocation *CommaLocs,
6346 SourceLocation RParenLoc) {
6347 // Dig out the member expression. This holds both the object
6348 // argument and the member function we're referring to.
John McCall10eae182009-11-30 22:42:35 +00006349 Expr *NakedMemExpr = MemExprE->IgnoreParens();
6350
John McCall10eae182009-11-30 22:42:35 +00006351 MemberExpr *MemExpr;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006352 CXXMethodDecl *Method = 0;
John McCall3a65ef42010-04-08 00:13:37 +00006353 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00006354 NestedNameSpecifier *Qualifier = 0;
John McCall10eae182009-11-30 22:42:35 +00006355 if (isa<MemberExpr>(NakedMemExpr)) {
6356 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall10eae182009-11-30 22:42:35 +00006357 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall16df1e52010-03-30 21:47:33 +00006358 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregorcc3f3252010-03-03 23:55:11 +00006359 Qualifier = MemExpr->getQualifier();
John McCall10eae182009-11-30 22:42:35 +00006360 } else {
6361 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00006362 Qualifier = UnresExpr->getQualifier();
6363
John McCall6e9f8f62009-12-03 04:06:58 +00006364 QualType ObjectType = UnresExpr->getBaseType();
John McCall10eae182009-11-30 22:42:35 +00006365
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006366 // Add overload candidates
John McCallbc077cf2010-02-08 23:07:23 +00006367 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
Mike Stump11289f42009-09-09 15:08:12 +00006368
John McCall2d74de92009-12-01 22:10:20 +00006369 // FIXME: avoid copy.
6370 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
6371 if (UnresExpr->hasExplicitTemplateArgs()) {
6372 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
6373 TemplateArgs = &TemplateArgsBuffer;
6374 }
6375
John McCall10eae182009-11-30 22:42:35 +00006376 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
6377 E = UnresExpr->decls_end(); I != E; ++I) {
6378
John McCall6e9f8f62009-12-03 04:06:58 +00006379 NamedDecl *Func = *I;
6380 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
6381 if (isa<UsingShadowDecl>(Func))
6382 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
6383
John McCall10eae182009-11-30 22:42:35 +00006384 if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregord3319842009-10-24 04:59:53 +00006385 // If explicit template arguments were provided, we can't call a
6386 // non-template member function.
John McCall2d74de92009-12-01 22:10:20 +00006387 if (TemplateArgs)
Douglas Gregord3319842009-10-24 04:59:53 +00006388 continue;
6389
John McCalla0296f72010-03-19 07:35:19 +00006390 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
John McCallb89836b2010-01-26 01:37:31 +00006391 Args, NumArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00006392 CandidateSet, /*SuppressUserConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +00006393 } else {
John McCall10eae182009-11-30 22:42:35 +00006394 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCalla0296f72010-03-19 07:35:19 +00006395 I.getPair(), ActingDC, TemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00006396 ObjectType, Args, NumArgs,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00006397 CandidateSet,
6398 /*SuppressUsedConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +00006399 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00006400 }
Mike Stump11289f42009-09-09 15:08:12 +00006401
John McCall10eae182009-11-30 22:42:35 +00006402 DeclarationName DeclName = UnresExpr->getMemberName();
6403
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006404 OverloadCandidateSet::iterator Best;
John McCall10eae182009-11-30 22:42:35 +00006405 switch (BestViableFunction(CandidateSet, UnresExpr->getLocStart(), Best)) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006406 case OR_Success:
6407 Method = cast<CXXMethodDecl>(Best->Function);
John McCall16df1e52010-03-30 21:47:33 +00006408 FoundDecl = Best->FoundDecl;
John McCalla0296f72010-03-19 07:35:19 +00006409 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006410 break;
6411
6412 case OR_No_Viable_Function:
John McCall10eae182009-11-30 22:42:35 +00006413 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006414 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00006415 << DeclName << MemExprE->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006416 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006417 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00006418 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006419
6420 case OR_Ambiguous:
John McCall10eae182009-11-30 22:42:35 +00006421 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00006422 << DeclName << MemExprE->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006423 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006424 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00006425 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00006426
6427 case OR_Deleted:
John McCall10eae182009-11-30 22:42:35 +00006428 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor171c45a2009-02-18 21:56:37 +00006429 << Best->Function->isDeleted()
Douglas Gregor97628d62009-08-21 00:16:32 +00006430 << DeclName << MemExprE->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006431 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00006432 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00006433 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006434 }
6435
John McCall16df1e52010-03-30 21:47:33 +00006436 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCall2d74de92009-12-01 22:10:20 +00006437
John McCall2d74de92009-12-01 22:10:20 +00006438 // If overload resolution picked a static member, build a
6439 // non-member call based on that function.
6440 if (Method->isStatic()) {
6441 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
6442 Args, NumArgs, RParenLoc);
6443 }
6444
John McCall10eae182009-11-30 22:42:35 +00006445 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006446 }
6447
6448 assert(Method && "Member call to something that isn't a method?");
Mike Stump11289f42009-09-09 15:08:12 +00006449 ExprOwningPtr<CXXMemberCallExpr>
John McCall2d74de92009-12-01 22:10:20 +00006450 TheCall(this, new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
Mike Stump11289f42009-09-09 15:08:12 +00006451 NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006452 Method->getResultType().getNonReferenceType(),
6453 RParenLoc));
6454
Anders Carlssonc4859ba2009-10-10 00:06:20 +00006455 // Check for a valid return type.
6456 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
6457 TheCall.get(), Method))
John McCall2d74de92009-12-01 22:10:20 +00006458 return ExprError();
Anders Carlssonc4859ba2009-10-10 00:06:20 +00006459
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006460 // Convert the object argument (for a non-static member function call).
John McCall16df1e52010-03-30 21:47:33 +00006461 // We only need to do this if there was actually an overload; otherwise
6462 // it was done at lookup.
John McCall2d74de92009-12-01 22:10:20 +00006463 Expr *ObjectArg = MemExpr->getBase();
Mike Stump11289f42009-09-09 15:08:12 +00006464 if (!Method->isStatic() &&
John McCall16df1e52010-03-30 21:47:33 +00006465 PerformObjectArgumentInitialization(ObjectArg, Qualifier,
6466 FoundDecl, Method))
John McCall2d74de92009-12-01 22:10:20 +00006467 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006468 MemExpr->setBase(ObjectArg);
6469
6470 // Convert the rest of the arguments
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006471 const FunctionProtoType *Proto = cast<FunctionProtoType>(Method->getType());
Mike Stump11289f42009-09-09 15:08:12 +00006472 if (ConvertArgumentsForCall(&*TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006473 RParenLoc))
John McCall2d74de92009-12-01 22:10:20 +00006474 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006475
Anders Carlssonbc4c1072009-08-16 01:56:34 +00006476 if (CheckFunctionCall(Method, TheCall.get()))
John McCall2d74de92009-12-01 22:10:20 +00006477 return ExprError();
Anders Carlsson8c84c202009-08-16 03:42:12 +00006478
John McCall2d74de92009-12-01 22:10:20 +00006479 return MaybeBindToTemporary(TheCall.release());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006480}
6481
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006482/// BuildCallToObjectOfClassType - Build a call to an object of class
6483/// type (C++ [over.call.object]), which can end up invoking an
6484/// overloaded function call operator (@c operator()) or performing a
6485/// user-defined conversion on the object argument.
Mike Stump11289f42009-09-09 15:08:12 +00006486Sema::ExprResult
6487Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
Douglas Gregorb0846b02008-12-06 00:22:45 +00006488 SourceLocation LParenLoc,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006489 Expr **Args, unsigned NumArgs,
Mike Stump11289f42009-09-09 15:08:12 +00006490 SourceLocation *CommaLocs,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006491 SourceLocation RParenLoc) {
6492 assert(Object->getType()->isRecordType() && "Requires object type argument");
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006493 const RecordType *Record = Object->getType()->getAs<RecordType>();
Mike Stump11289f42009-09-09 15:08:12 +00006494
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006495 // C++ [over.call.object]p1:
6496 // If the primary-expression E in the function call syntax
Eli Friedman44b83ee2009-08-05 19:21:58 +00006497 // evaluates to a class object of type "cv T", then the set of
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006498 // candidate functions includes at least the function call
6499 // operators of T. The function call operators of T are obtained by
6500 // ordinary lookup of the name operator() in the context of
6501 // (E).operator().
John McCallbc077cf2010-02-08 23:07:23 +00006502 OverloadCandidateSet CandidateSet(LParenLoc);
Douglas Gregor91f84212008-12-11 16:49:14 +00006503 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregorc473cbb2009-11-15 07:48:03 +00006504
6505 if (RequireCompleteType(LParenLoc, Object->getType(),
Douglas Gregor89336232010-03-29 23:34:08 +00006506 PDiag(diag::err_incomplete_object_call)
Douglas Gregorc473cbb2009-11-15 07:48:03 +00006507 << Object->getSourceRange()))
6508 return true;
6509
John McCall27b18f82009-11-17 02:14:36 +00006510 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
6511 LookupQualifiedName(R, Record->getDecl());
6512 R.suppressDiagnostics();
6513
Douglas Gregorc473cbb2009-11-15 07:48:03 +00006514 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor358e7742009-11-07 17:23:56 +00006515 Oper != OperEnd; ++Oper) {
John McCalla0296f72010-03-19 07:35:19 +00006516 AddMethodCandidate(Oper.getPair(), Object->getType(),
John McCallb89836b2010-01-26 01:37:31 +00006517 Args, NumArgs, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00006518 /*SuppressUserConversions=*/ false);
Douglas Gregor358e7742009-11-07 17:23:56 +00006519 }
Douglas Gregor74ba25c2009-10-21 06:18:39 +00006520
Douglas Gregorab7897a2008-11-19 22:57:39 +00006521 // C++ [over.call.object]p2:
6522 // In addition, for each conversion function declared in T of the
6523 // form
6524 //
6525 // operator conversion-type-id () cv-qualifier;
6526 //
6527 // where cv-qualifier is the same cv-qualification as, or a
6528 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregorf49fdf82008-11-20 13:33:37 +00006529 // denotes the type "pointer to function of (P1,...,Pn) returning
6530 // R", or the type "reference to pointer to function of
6531 // (P1,...,Pn) returning R", or the type "reference to function
6532 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregorab7897a2008-11-19 22:57:39 +00006533 // is also considered as a candidate function. Similarly,
6534 // surrogate call functions are added to the set of candidate
6535 // functions for each conversion function declared in an
6536 // accessible base class provided the function is not hidden
6537 // within T by another intervening declaration.
John McCallad371252010-01-20 00:46:10 +00006538 const UnresolvedSetImpl *Conversions
Douglas Gregor21591822010-01-11 19:36:35 +00006539 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00006540 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00006541 E = Conversions->end(); I != E; ++I) {
John McCall6e9f8f62009-12-03 04:06:58 +00006542 NamedDecl *D = *I;
6543 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
6544 if (isa<UsingShadowDecl>(D))
6545 D = cast<UsingShadowDecl>(D)->getTargetDecl();
6546
Douglas Gregor74ba25c2009-10-21 06:18:39 +00006547 // Skip over templated conversion functions; they aren't
6548 // surrogates.
John McCall6e9f8f62009-12-03 04:06:58 +00006549 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor74ba25c2009-10-21 06:18:39 +00006550 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00006551
John McCall6e9f8f62009-12-03 04:06:58 +00006552 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
John McCalld14a8642009-11-21 08:51:07 +00006553
Douglas Gregor74ba25c2009-10-21 06:18:39 +00006554 // Strip the reference type (if any) and then the pointer type (if
6555 // any) to get down to what might be a function type.
6556 QualType ConvType = Conv->getConversionType().getNonReferenceType();
6557 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
6558 ConvType = ConvPtrType->getPointeeType();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006559
Douglas Gregor74ba25c2009-10-21 06:18:39 +00006560 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
John McCalla0296f72010-03-19 07:35:19 +00006561 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
John McCall6e9f8f62009-12-03 04:06:58 +00006562 Object->getType(), Args, NumArgs,
6563 CandidateSet);
Douglas Gregorab7897a2008-11-19 22:57:39 +00006564 }
Mike Stump11289f42009-09-09 15:08:12 +00006565
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006566 // Perform overload resolution.
6567 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006568 switch (BestViableFunction(CandidateSet, Object->getLocStart(), Best)) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006569 case OR_Success:
Douglas Gregorab7897a2008-11-19 22:57:39 +00006570 // Overload resolution succeeded; we'll build the appropriate call
6571 // below.
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006572 break;
6573
6574 case OR_No_Viable_Function:
John McCall02374852010-01-07 02:04:15 +00006575 if (CandidateSet.empty())
6576 Diag(Object->getSourceRange().getBegin(), diag::err_ovl_no_oper)
6577 << Object->getType() << /*call*/ 1
6578 << Object->getSourceRange();
6579 else
6580 Diag(Object->getSourceRange().getBegin(),
6581 diag::err_ovl_no_viable_object_call)
6582 << Object->getType() << Object->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006583 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006584 break;
6585
6586 case OR_Ambiguous:
6587 Diag(Object->getSourceRange().getBegin(),
6588 diag::err_ovl_ambiguous_object_call)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006589 << Object->getType() << Object->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006590 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006591 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00006592
6593 case OR_Deleted:
6594 Diag(Object->getSourceRange().getBegin(),
6595 diag::err_ovl_deleted_object_call)
6596 << Best->Function->isDeleted()
6597 << Object->getType() << Object->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006598 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00006599 break;
Mike Stump11289f42009-09-09 15:08:12 +00006600 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006601
Douglas Gregorab7897a2008-11-19 22:57:39 +00006602 if (Best == CandidateSet.end()) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006603 // We had an error; delete all of the subexpressions and return
6604 // the error.
Ted Kremenek5a201952009-02-07 01:47:29 +00006605 Object->Destroy(Context);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006606 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Ted Kremenek5a201952009-02-07 01:47:29 +00006607 Args[ArgIdx]->Destroy(Context);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006608 return true;
6609 }
6610
Douglas Gregorab7897a2008-11-19 22:57:39 +00006611 if (Best->Function == 0) {
6612 // Since there is no function declaration, this is one of the
6613 // surrogate candidates. Dig out the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +00006614 CXXConversionDecl *Conv
Douglas Gregorab7897a2008-11-19 22:57:39 +00006615 = cast<CXXConversionDecl>(
6616 Best->Conversions[0].UserDefined.ConversionFunction);
6617
John McCalla0296f72010-03-19 07:35:19 +00006618 CheckMemberOperatorAccess(LParenLoc, Object, 0, Best->FoundDecl);
John McCall49ec2e62010-01-28 01:54:34 +00006619
Douglas Gregorab7897a2008-11-19 22:57:39 +00006620 // We selected one of the surrogate functions that converts the
6621 // object parameter to a function pointer. Perform the conversion
6622 // on the object argument, then let ActOnCallExpr finish the job.
Fariborz Jahanian774cf792009-09-28 18:35:46 +00006623
6624 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00006625 // and then call it.
John McCall16df1e52010-03-30 21:47:33 +00006626 CXXMemberCallExpr *CE = BuildCXXMemberCallExpr(Object, Best->FoundDecl,
6627 Conv);
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00006628
Fariborz Jahanian774cf792009-09-28 18:35:46 +00006629 return ActOnCallExpr(S, ExprArg(*this, CE), LParenLoc,
Sebastian Redlc215cfc2009-01-19 00:08:26 +00006630 MultiExprArg(*this, (ExprTy**)Args, NumArgs),
Douglas Gregore5e775b2010-04-13 15:50:39 +00006631 CommaLocs, RParenLoc).result();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006632 }
6633
John McCalla0296f72010-03-19 07:35:19 +00006634 CheckMemberOperatorAccess(LParenLoc, Object, 0, Best->FoundDecl);
John McCall49ec2e62010-01-28 01:54:34 +00006635
Douglas Gregorab7897a2008-11-19 22:57:39 +00006636 // We found an overloaded operator(). Build a CXXOperatorCallExpr
6637 // that calls this method, using Object for the implicit object
6638 // parameter and passing along the remaining arguments.
6639 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John McCall9dd450b2009-09-21 23:43:11 +00006640 const FunctionProtoType *Proto = Method->getType()->getAs<FunctionProtoType>();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006641
6642 unsigned NumArgsInProto = Proto->getNumArgs();
6643 unsigned NumArgsToCheck = NumArgs;
6644
6645 // Build the full argument list for the method call (the
6646 // implicit object parameter is placed at the beginning of the
6647 // list).
6648 Expr **MethodArgs;
6649 if (NumArgs < NumArgsInProto) {
6650 NumArgsToCheck = NumArgsInProto;
6651 MethodArgs = new Expr*[NumArgsInProto + 1];
6652 } else {
6653 MethodArgs = new Expr*[NumArgs + 1];
6654 }
6655 MethodArgs[0] = Object;
6656 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
6657 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump11289f42009-09-09 15:08:12 +00006658
6659 Expr *NewFn = new (Context) DeclRefExpr(Method, Method->getType(),
Ted Kremenek5a201952009-02-07 01:47:29 +00006660 SourceLocation());
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006661 UsualUnaryConversions(NewFn);
6662
6663 // Once we've built TheCall, all of the expressions are properly
6664 // owned.
6665 QualType ResultTy = Method->getResultType().getNonReferenceType();
Mike Stump11289f42009-09-09 15:08:12 +00006666 ExprOwningPtr<CXXOperatorCallExpr>
6667 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006668 MethodArgs, NumArgs + 1,
Ted Kremenek5a201952009-02-07 01:47:29 +00006669 ResultTy, RParenLoc));
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006670 delete [] MethodArgs;
6671
Anders Carlsson3d5829c2009-10-13 21:49:31 +00006672 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall.get(),
6673 Method))
6674 return true;
6675
Douglas Gregor02a0acd2009-01-13 05:10:00 +00006676 // We may have default arguments. If so, we need to allocate more
6677 // slots in the call for them.
6678 if (NumArgs < NumArgsInProto)
Ted Kremenek5a201952009-02-07 01:47:29 +00006679 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor02a0acd2009-01-13 05:10:00 +00006680 else if (NumArgs > NumArgsInProto)
6681 NumArgsToCheck = NumArgsInProto;
6682
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00006683 bool IsError = false;
6684
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006685 // Initialize the implicit object parameter.
Douglas Gregorcc3f3252010-03-03 23:55:11 +00006686 IsError |= PerformObjectArgumentInitialization(Object, /*Qualifier=*/0,
John McCall16df1e52010-03-30 21:47:33 +00006687 Best->FoundDecl, Method);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006688 TheCall->setArg(0, Object);
6689
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00006690
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006691 // Check the argument types.
6692 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006693 Expr *Arg;
Douglas Gregor02a0acd2009-01-13 05:10:00 +00006694 if (i < NumArgs) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006695 Arg = Args[i];
Mike Stump11289f42009-09-09 15:08:12 +00006696
Douglas Gregor02a0acd2009-01-13 05:10:00 +00006697 // Pass the argument.
Anders Carlsson7c5fe482010-01-29 18:43:53 +00006698
6699 OwningExprResult InputInit
6700 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
6701 Method->getParamDecl(i)),
6702 SourceLocation(), Owned(Arg));
6703
6704 IsError |= InputInit.isInvalid();
6705 Arg = InputInit.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +00006706 } else {
Douglas Gregor1bc688d2009-11-09 19:27:57 +00006707 OwningExprResult DefArg
6708 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
6709 if (DefArg.isInvalid()) {
6710 IsError = true;
6711 break;
6712 }
6713
6714 Arg = DefArg.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +00006715 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006716
6717 TheCall->setArg(i + 1, Arg);
6718 }
6719
6720 // If this is a variadic call, handle args passed through "...".
6721 if (Proto->isVariadic()) {
6722 // Promote the arguments (C99 6.5.2.2p7).
6723 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
6724 Expr *Arg = Args[i];
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00006725 IsError |= DefaultVariadicArgumentPromotion(Arg, VariadicMethod);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006726 TheCall->setArg(i + 1, Arg);
6727 }
6728 }
6729
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00006730 if (IsError) return true;
6731
Anders Carlssonbc4c1072009-08-16 01:56:34 +00006732 if (CheckFunctionCall(Method, TheCall.get()))
6733 return true;
6734
Douglas Gregore5e775b2010-04-13 15:50:39 +00006735 return MaybeBindToTemporary(TheCall.release()).result();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006736}
6737
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006738/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump11289f42009-09-09 15:08:12 +00006739/// (if one exists), where @c Base is an expression of class type and
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006740/// @c Member is the name of the member we're trying to find.
Douglas Gregord8061562009-08-06 03:17:00 +00006741Sema::OwningExprResult
6742Sema::BuildOverloadedArrowExpr(Scope *S, ExprArg BaseIn, SourceLocation OpLoc) {
6743 Expr *Base = static_cast<Expr *>(BaseIn.get());
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006744 assert(Base->getType()->isRecordType() && "left-hand side must have class type");
Mike Stump11289f42009-09-09 15:08:12 +00006745
John McCallbc077cf2010-02-08 23:07:23 +00006746 SourceLocation Loc = Base->getExprLoc();
6747
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006748 // C++ [over.ref]p1:
6749 //
6750 // [...] An expression x->m is interpreted as (x.operator->())->m
6751 // for a class object x of type T if T::operator->() exists and if
6752 // the operator is selected as the best match function by the
6753 // overload resolution mechanism (13.3).
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006754 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
John McCallbc077cf2010-02-08 23:07:23 +00006755 OverloadCandidateSet CandidateSet(Loc);
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006756 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregord8061562009-08-06 03:17:00 +00006757
John McCallbc077cf2010-02-08 23:07:23 +00006758 if (RequireCompleteType(Loc, Base->getType(),
Eli Friedman132e70b2009-11-18 01:28:03 +00006759 PDiag(diag::err_typecheck_incomplete_tag)
6760 << Base->getSourceRange()))
6761 return ExprError();
6762
John McCall27b18f82009-11-17 02:14:36 +00006763 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
6764 LookupQualifiedName(R, BaseRecord->getDecl());
6765 R.suppressDiagnostics();
Anders Carlsson78b54932009-09-10 23:18:36 +00006766
6767 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall6e9f8f62009-12-03 04:06:58 +00006768 Oper != OperEnd; ++Oper) {
John McCalla0296f72010-03-19 07:35:19 +00006769 AddMethodCandidate(Oper.getPair(), Base->getType(), 0, 0, CandidateSet,
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006770 /*SuppressUserConversions=*/false);
John McCall6e9f8f62009-12-03 04:06:58 +00006771 }
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006772
6773 // Perform overload resolution.
6774 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006775 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006776 case OR_Success:
6777 // Overload resolution succeeded; we'll build the call below.
6778 break;
6779
6780 case OR_No_Viable_Function:
6781 if (CandidateSet.empty())
6782 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregord8061562009-08-06 03:17:00 +00006783 << Base->getType() << Base->getSourceRange();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006784 else
6785 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregord8061562009-08-06 03:17:00 +00006786 << "operator->" << Base->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006787 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00006788 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006789
6790 case OR_Ambiguous:
6791 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
Anders Carlsson78b54932009-09-10 23:18:36 +00006792 << "->" << Base->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006793 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00006794 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00006795
6796 case OR_Deleted:
6797 Diag(OpLoc, diag::err_ovl_deleted_oper)
6798 << Best->Function->isDeleted()
Anders Carlsson78b54932009-09-10 23:18:36 +00006799 << "->" << Base->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006800 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00006801 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006802 }
6803
John McCalla0296f72010-03-19 07:35:19 +00006804 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl);
6805
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006806 // Convert the object parameter.
6807 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John McCall16df1e52010-03-30 21:47:33 +00006808 if (PerformObjectArgumentInitialization(Base, /*Qualifier=*/0,
6809 Best->FoundDecl, Method))
Douglas Gregord8061562009-08-06 03:17:00 +00006810 return ExprError();
Douglas Gregor9ecea262008-11-21 03:04:22 +00006811
6812 // No concerns about early exits now.
Douglas Gregord8061562009-08-06 03:17:00 +00006813 BaseIn.release();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006814
6815 // Build the operator call.
Ted Kremenek5a201952009-02-07 01:47:29 +00006816 Expr *FnExpr = new (Context) DeclRefExpr(Method, Method->getType(),
6817 SourceLocation());
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006818 UsualUnaryConversions(FnExpr);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00006819
6820 QualType ResultTy = Method->getResultType().getNonReferenceType();
6821 ExprOwningPtr<CXXOperatorCallExpr>
6822 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr,
6823 &Base, 1, ResultTy, OpLoc));
6824
6825 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall.get(),
6826 Method))
6827 return ExprError();
6828 return move(TheCall);
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006829}
6830
Douglas Gregorcd695e52008-11-10 20:40:00 +00006831/// FixOverloadedFunctionReference - E is an expression that refers to
6832/// a C++ overloaded function (possibly with some parentheses and
6833/// perhaps a '&' around it). We have resolved the overloaded function
6834/// to the function declaration Fn, so patch up the expression E to
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00006835/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCalla8ae2222010-04-06 21:38:20 +00006836Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall16df1e52010-03-30 21:47:33 +00006837 FunctionDecl *Fn) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00006838 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +00006839 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
6840 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +00006841 if (SubExpr == PE->getSubExpr())
6842 return PE->Retain();
6843
6844 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
6845 }
6846
6847 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +00006848 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
6849 Found, Fn);
Douglas Gregor091f0422009-10-23 22:18:25 +00006850 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor51c538b2009-11-20 19:42:02 +00006851 SubExpr->getType()) &&
Douglas Gregor091f0422009-10-23 22:18:25 +00006852 "Implicit cast type cannot be determined from overload");
Douglas Gregor51c538b2009-11-20 19:42:02 +00006853 if (SubExpr == ICE->getSubExpr())
6854 return ICE->Retain();
6855
6856 return new (Context) ImplicitCastExpr(ICE->getType(),
6857 ICE->getCastKind(),
6858 SubExpr,
6859 ICE->isLvalueCast());
6860 }
6861
6862 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
Mike Stump11289f42009-09-09 15:08:12 +00006863 assert(UnOp->getOpcode() == UnaryOperator::AddrOf &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00006864 "Can only take the address of an overloaded function");
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006865 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
6866 if (Method->isStatic()) {
6867 // Do nothing: static member functions aren't any different
6868 // from non-member functions.
John McCalld14a8642009-11-21 08:51:07 +00006869 } else {
John McCalle66edc12009-11-24 19:00:30 +00006870 // Fix the sub expression, which really has to be an
6871 // UnresolvedLookupExpr holding an overloaded member function
6872 // or template.
John McCall16df1e52010-03-30 21:47:33 +00006873 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
6874 Found, Fn);
John McCalld14a8642009-11-21 08:51:07 +00006875 if (SubExpr == UnOp->getSubExpr())
6876 return UnOp->Retain();
Douglas Gregor51c538b2009-11-20 19:42:02 +00006877
John McCalld14a8642009-11-21 08:51:07 +00006878 assert(isa<DeclRefExpr>(SubExpr)
6879 && "fixed to something other than a decl ref");
6880 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
6881 && "fixed to a member ref with no nested name qualifier");
6882
6883 // We have taken the address of a pointer to member
6884 // function. Perform the computation here so that we get the
6885 // appropriate pointer to member type.
6886 QualType ClassType
6887 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
6888 QualType MemPtrType
6889 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
6890
6891 return new (Context) UnaryOperator(SubExpr, UnaryOperator::AddrOf,
6892 MemPtrType, UnOp->getOperatorLoc());
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006893 }
6894 }
John McCall16df1e52010-03-30 21:47:33 +00006895 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
6896 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +00006897 if (SubExpr == UnOp->getSubExpr())
6898 return UnOp->Retain();
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00006899
Douglas Gregor51c538b2009-11-20 19:42:02 +00006900 return new (Context) UnaryOperator(SubExpr, UnaryOperator::AddrOf,
6901 Context.getPointerType(SubExpr->getType()),
6902 UnOp->getOperatorLoc());
Douglas Gregor51c538b2009-11-20 19:42:02 +00006903 }
John McCalld14a8642009-11-21 08:51:07 +00006904
6905 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCall2d74de92009-12-01 22:10:20 +00006906 // FIXME: avoid copy.
6907 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
John McCalle66edc12009-11-24 19:00:30 +00006908 if (ULE->hasExplicitTemplateArgs()) {
John McCall2d74de92009-12-01 22:10:20 +00006909 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
6910 TemplateArgs = &TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +00006911 }
6912
John McCalld14a8642009-11-21 08:51:07 +00006913 return DeclRefExpr::Create(Context,
6914 ULE->getQualifier(),
6915 ULE->getQualifierRange(),
6916 Fn,
6917 ULE->getNameLoc(),
John McCall2d74de92009-12-01 22:10:20 +00006918 Fn->getType(),
6919 TemplateArgs);
John McCalld14a8642009-11-21 08:51:07 +00006920 }
6921
John McCall10eae182009-11-30 22:42:35 +00006922 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCall6b51f282009-11-23 01:53:49 +00006923 // FIXME: avoid copy.
John McCall2d74de92009-12-01 22:10:20 +00006924 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
6925 if (MemExpr->hasExplicitTemplateArgs()) {
6926 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
6927 TemplateArgs = &TemplateArgsBuffer;
6928 }
John McCall6b51f282009-11-23 01:53:49 +00006929
John McCall2d74de92009-12-01 22:10:20 +00006930 Expr *Base;
6931
6932 // If we're filling in
6933 if (MemExpr->isImplicitAccess()) {
6934 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
6935 return DeclRefExpr::Create(Context,
6936 MemExpr->getQualifier(),
6937 MemExpr->getQualifierRange(),
6938 Fn,
6939 MemExpr->getMemberLoc(),
6940 Fn->getType(),
6941 TemplateArgs);
Douglas Gregorb15af892010-01-07 23:12:05 +00006942 } else {
6943 SourceLocation Loc = MemExpr->getMemberLoc();
6944 if (MemExpr->getQualifier())
6945 Loc = MemExpr->getQualifierRange().getBegin();
6946 Base = new (Context) CXXThisExpr(Loc,
6947 MemExpr->getBaseType(),
6948 /*isImplicit=*/true);
6949 }
John McCall2d74de92009-12-01 22:10:20 +00006950 } else
6951 Base = MemExpr->getBase()->Retain();
6952
6953 return MemberExpr::Create(Context, Base,
Douglas Gregor51c538b2009-11-20 19:42:02 +00006954 MemExpr->isArrow(),
6955 MemExpr->getQualifier(),
6956 MemExpr->getQualifierRange(),
6957 Fn,
John McCall16df1e52010-03-30 21:47:33 +00006958 Found,
John McCall6b51f282009-11-23 01:53:49 +00006959 MemExpr->getMemberLoc(),
John McCall2d74de92009-12-01 22:10:20 +00006960 TemplateArgs,
Douglas Gregor51c538b2009-11-20 19:42:02 +00006961 Fn->getType());
6962 }
6963
Douglas Gregor51c538b2009-11-20 19:42:02 +00006964 assert(false && "Invalid reference to overloaded function");
6965 return E->Retain();
Douglas Gregorcd695e52008-11-10 20:40:00 +00006966}
6967
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006968Sema::OwningExprResult Sema::FixOverloadedFunctionReference(OwningExprResult E,
John McCalla8ae2222010-04-06 21:38:20 +00006969 DeclAccessPair Found,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006970 FunctionDecl *Fn) {
John McCall16df1e52010-03-30 21:47:33 +00006971 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn));
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006972}
6973
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006974} // end namespace clang